I am trying to understand how Python implements OO. I’m trying to understand how I can use an existing class within my class – so as much of the processing is hidden as possible from the programmer. The exercise I have created is to write a Class Rect that can be used to create an object that has two attributes : len and wid and (somehow) will “contain” another object – which I will call “stylus”. My idea is when I instantiate an object of class Rect, I will pass the length and width of the rectangle and a “stylus” created by
stylus = turtle.Turtle()
Say the Rect object created is rect_obj, then I want to define a method, draw_rect, in Rect that will draw the rectangle. My code attempt is below (*) (which of course doesn’t work).
(*)
class Rect:
def __init__(self,rect_len,rect_wid,stylus_in):
self.len = rect_len
self.wid = rect_wid
self.stylus = stylus_in
#
def draw_rect(self,stylus):
self.stylus.forward(len)
self.stylus.right(90)
# class Square(Rect):
def __init__(self,side_len):
self.len = side_len
self.wid = side_len
import turtle stylus = turtle.Turtle()
rect_obj = Rect(int(5),int(4),stylus)
stylus = turtle.Turtle()
print(rect_obj.len)
print(rect_obj.wid)
rect_obj.draw_rect(stylus)
I’m trying to understand how I code the Python so I hide this processing and all that needs to be written is something like:
rect_obj.draw_rect(stylus)
Now, when I run my code it fails in turtle.py with following error messages:
*** Remote Interpreter Reinitialized *** 5 4 Traceback (most recent call last): File "C:\Users\Clive\Desktop\temp_OOP_turtle.py", line
27, in <module>
rect_obj.draw_rect(stylus) File "C:\Users\Clive\Desktop\temp_OOP_turtle.py", line 12, in draw_rect
self.stylus.forward(len) File "C:\Users\Clive\AppData\Local\Programs\Python\Python37\lib\turtle.py",
line 1637, in forward
self._go(distance) File "C:\Users\Clive\AppData\Local\Programs\Python\Python37\lib\turtle.py",
line 1604, in _go
ende = self._position self._orient * distance File "C:\Users\Clive\AppData\Local\Programs\Python\Python37\lib\turtle.py",
line 257, in __mul__
return Vec2D(self[0]*other, self[1]*other) TypeError: unsupported operand type(s) for *: 'float' and 'builtin_function_or_method'
Is there anyway I can fix my Python so the code for moving the turtle is provided in a method inside Rect class?
I can get my stylus to draw a rectangle if I put the code currently in draw_rect at the “level” of my main routine (see end **) but that doesn't hide the code that draws the rectangle.
(**) Code that will draw a 50 x 70 rectangle but outside the class Rect: import turtle
smart = turtle.Turtle()
for i in range(2):
smart.forward(50)
smart.right(90)
smart.forward(70)
smart.right(90)
CodePudding user response:
Answer from comment by @topsail:
in draw_rect
you have this mistake: self.stylus.forward(len)
should be self.stylus.forward(self.len)