我用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'
使用super(),这是执行继承时的一种python方法。你知道吗
而不是写作
把它改成
在else块中也是如此。你知道吗
您应该调用
self.forward(50)
,而不是LTurtle.forward(50)
您已经对类名调用了
forward()
方法,只有在该方法是静态的情况下才能这样做。因为,forward()
方法是一个实例方法,所以您需要一个对象来调用它。你知道吗对象
my_interpreter
是类Interpreter
的对象,类是LTurtle
的子类。因此,这里使用self
引用对象my_interpreter
,并继承类LTurtle
。你知道吗因此,可以使用
self
调用类LTurtle
的方法,如下所示:这会解决你的问题。你知道吗
相关问题 更多 >
编程相关推荐