【问题标题】:Some questions regarding __init_ errors in python关于 python 中的 __init_ 错误的一些问题
【发布时间】:2020-12-26 10:44:04
【问题描述】:

我收到错误:TypeError: init() missing 1 required positional argument: 'attack'

    class Unit:
        def __init__(self, name):
            self.name = name
     
    class Power(Unit):
        def __init__(self, name, attack):
            Unit.__init__(self, name)
            self.attack = attack
            supatt = attack * 2
            print("{0} has a power of {1} and it can develop {1} 
            of its superpowers".format(self.name, attack, supatt))

    class Ground(Power):
        def __init__(self, name, attack, velocity, friction):
            Power.__init__(self, attack)
            self.velocity = velocity
            self.friction = friction
            totalv = velocity - fiction 
            print("{0} : Groud Attack. \nTotal Speed : {1}.\n 
            Power : {2}.".format(self.name, totalv, attack))
    
    class Sky(Power):
        def __init__(self, name, attack, skyspeed, airres):
            Power.__init__(self, attack)
            self.skyspeed = skyspeed
            self.airres = airres
            totalss = skyspeed - airres
            print("{0} : Sky Attack. \nTotal Speed : {1}.\n Power 
            : {2}.".format(self.name, totalss, attack))

    
    valkyrie = Sky("Valkyrie", 200, 300, 150)
    print(valkyrie)

错误出现在我写的 Sky(Power) 类中: Power.__init__(self, attack)

我以为我已经在这里写了attack。这段代码有什么问题?

【问题讨论】:

  • 您的 Power 类也需要 2 个参数,而您只提供了 1 个。由于两者都是位置性的,它仍然希望将某些东西传递给“攻击”
  • 看来您也只是忘记将name 向上传递。
  • Power.__init__(self,name, attack)

标签: python python-3.x init


【解决方案1】:

您试图将 Power 类继承给除 Unit 类之外的所有其他类。

您想使用 super() 函数继承类。

class Unit:
    def __init__(self, name):
        self.name = name

class Power(Unit):
    def __init__(self, name, attack):
        Unit.__init__(self, name)
        self.attack = attack
        supatt = attack * 2
        print("{0} has a power of {1} and it can develop {1} of its 
        superpowers".format(self.name, attack, supatt))

class Sky(Power):
    def __init__(self, name, attack, skyspeed, airres):
        super().__init__(self, attack)
        self.skyspeed = skyspeed
        self.airres = airres
        totalss = skyspeed - airres
        print("{0} : Sky Attack. \nTotal Speed : {1}.\n Power: 
        {2}.".format(self.name, totalss, attack))

class Ground(Power):
    def __init__(self, name, attack, velocity, friction):
        super().__init__(self, attack)
        self.velocity = velocity
        self.friction = friction
        totalv = velocity - friction
        print("{0} : Groud Attack. \nTotal Speed : {1}.\nPower : 
        {2}.".format(self.name, totalv, attack))


valkyrie = Sky("Valkyrie", 200, 300, 150)
print(valkyrie)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 2021-10-12
    • 1970-01-01
    • 2018-05-24
    相关资源
    最近更新 更多