从另一个文件继承类会产生错误

2024-10-01 07:16:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python编写了两个简单的类。我的父类放在一个名为“class\u turtle”的文件中,它是:

    class LTurtle:
        def __init__(self, line_width):
            self.line_width = line_width

        def forward(self, step_size):
            print(f"Move Forward = {step_size}")

        def rest(self):
            print(f"Turtle is resting right now")

我的子类放在一个名为“class\u解释器”的文件下,该文件使用LTurtle类。这是我的翻译课:

from class_turtle import LTurtle

class Interpreter(LTurtle):
    def __init__(self, axiom):
        self.axiom = axiom
        self.string = axiom

    def parser(self):
        for char in self.string:
            if char == 'F':
                LTurtle.forward(50)
            else:
                LTurtle.rest()


if __name__ == '__main__':
    my_interpreter = Interpreter("F")
    my_interpreter.parser()

我还将init.py文件放在文件夹中。我不知道应该在哪里向我的LTurtle类声明线宽,出现以下错误:

TypeError: forward() missing 1 required positional argument: 'step_size'

Tags: 文件selfrestsizeinitdefstepline
3条回答

使用super(),这是执行继承时的一种python方法。你知道吗

而不是写作

 LTurtle.forward(50)

把它改成

super().forward(50)

在else块中也是如此。你知道吗

您应该调用self.forward(50),而不是LTurtle.forward(50)

您已经对类名调用了forward()方法,只有在该方法是静态的情况下才能这样做。因为,forward()方法是一个实例方法,所以您需要一个对象来调用它。你知道吗

对象my_interpreter是类Interpreter的对象,类是LTurtle的子类。因此,这里使用self引用对象my_interpreter,并继承类LTurtle。你知道吗

因此,可以使用self调用类LTurtle的方法,如下所示:

def parser(self):
    for char in self.string:
        if char == 'F':
            self.forward(50)
        else:
            self.rest()

这会解决你的问题。你知道吗

相关问题 更多 >