【问题标题】:__init__() missing positional argument when calling class__init__() 调用类时缺少位置参数
【发布时间】:2023-03-22 17:40:01
【问题描述】:

我试图弄清楚为什么 init() 缺少一个参数,在这种情况下,当plane = Mywork.__init__( 'boeing', 747, 890) 行中给出了 3 个参数时会加快速度

这里是完整的代码,我想我没有做对第一个参数只是作为一个字符串而没有在任何地方指定,即使我使用了 str

我只想让代码执行 def str 并运行。

代码:

class Mywork(object):

    def __init__(self, manufacturer, model, speed): #Aircraft
        self.manufacturer = manufacturer
        self.model = model
        self.speed = speed

    def __str__(self):
        return 'This is a {self.manufacturer} {self.model}'.format(self=self)

    def run(self):
        print('Works')
        print(self.__str__())

plane = Mywork.__init__( 'boeing', 747, 890)

if __name__ == '__main__':
    Mywork()

【问题讨论】:

  • 显示堆栈跟踪。哪一行有错误? MyWork() 肯定不行。

标签: python python-3.x class arguments typeerror


【解决方案1】:

如果不先创建一个实例作为第一个参数传递,就不能直接调用__init__。以下是合法的,尽管没有人会编写这样的代码:

plane = Mywork.__new__(Mywork, 'boeing', 747, 980)
Mywork.__init__(plane, 'boeing', 747, 980)

想要的几乎是肯定的

class Mywork(object):
    ...

plane = Mywork('boeing', 747, 890)
...

你也没有真正明确地调用__str__;当你的类的实例作为参数传递时,你让str 这样做。

print(self.__str__())  # No!
print(str(self))  # Better
print(self)  # Best; print() already calls str as necessary to convert its arguments

【讨论】:

    【解决方案2】:
    if __name__ == '__main__':
        plane = Mywork('boeing', 747, 890)
        print(plane)
    

    输出:

    >>This is a boeing 747
    

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 2023-03-27
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 2022-01-11
      相关资源
      最近更新 更多