在类中使用预构建的Python类和方法

xmakbtuz  于 2022-12-27  发布在  Python
关注(0)|答案(1)|浏览(140)

我试图理解Python是如何实现面向对象的,我试图理解如何在类中使用现有的类,以便尽可能多地对程序员隐藏处理过程,我创建的练习是编写一个类矩形,用于创建具有两个属性的对象:len和wid,并且(以某种方式)将"包含"另一个对象--我称之为"手写笔"。我的想法是,当我示例化类Rect的对象时,我将传递矩形的长度和宽度以及由

stylus = turtle.Turtle()

假设创建的Rect对象是rect_obj,那么我想在Rect中定义一个方法draw_rect来绘制矩形,我的代码尝试如下()(当然不起作用)。

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)

我试着理解我是如何编写Python的,所以我隐藏了这个过程,所有需要写的东西就像这样:

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'

有没有什么办法可以修复我的Python,使移动海龟的代码在Rect类内部的方法中提供?
如果我把draw_rect中的代码放在主例程的"级别"上(参见end**),我可以用手写笔画一个矩形,但这并没有隐藏画矩形的代码。
)用于绘制50 x 70矩形但在类Rect之外的代码:进口甲鱼

smart = turtle.Turtle()
for i in range(2):
    smart.forward(50)
    smart.right(90)
    smart.forward(70)
    smart.right(90)
8yparm6h

8yparm6h1#

来自@topsail评论的回答:
draw_rect中,您会遇到以下错误:self.stylus.forward(len)应为self.stylus.forward(self.len)

相关问题