__init __()缺少1个必需的位置参数

时间:2018-04-18 23:05:09

标签: python initialization

    class Blaster(Weapon):
    def __init__(self, Range, accuracy):
        self.accuracy = accuracy
        self.Range = Range
        super()
blaster = Blaster(Weapon)

我是Python的新手,我正在制作游戏并使用类的项目。当我运行它时,错误代码是:

__init__() missing 1 required positional argument: 'accuracy'

我希望能够使用对象来保存不同项目的信息,并为用户打印出来。

超类:

class Item():
def __init__(self, name, description, value):
    self.name = name
    self.description = description
    self.value = value

class Weapon(Item):
    def __init__(self, damage, speed):
        self.damage = damage
        self.speed = speed
        super()

1 个答案:

答案 0 :(得分:0)

创建类的实例时,需要提供self函数的参数(__init__除外):

class Blaster():
    def __init__(self, Range, accuracy):
        self.accuracy = accuracy
        self.Range = Range

blaster_range = 50
blaster_accunary = 0.5
blaster = Blaster(blaster_range, blaster_accunary)

当然你也可以这样做,我用变量来弄清楚价值的意义。

blaster = Blaster(50, 0.5)

对于继承,你需要像这样(See Pyfiddle)一直传递所有参数:

class Item():
    def __init__(self, name, description, value):
        self.name = name
        self.description = description
        self.value = value

class Weapon(Item):
    def __init__(self, name, description, value, damage, speed):
        self.damage = damage
        self.speed = speed
        Item.__init__(self, name, description, value)

class Blaster(Weapon):
    def __init__(self, name, description, value, damage, speed, Range, accuracy):
        self.accuracy = accuracy
        self.Range = Range
        Weapon.__init__(self, name, description, value, damage, speed)

blaster = Blaster(
    name="MyBlaster",
    description="A huge weapon",
    value=10,
    damage=20,
    speed=30,
    Range=50,
    accuracy=0.5
)
print(blaster.name)
print(blaster.description)
print(blaster.value)
print(blaster.damage)
print(blaster.speed)
print(blaster.Range)
print(blaster.accuracy)

如果所有Blasters都有固定(例如)伤害和速度,那么你可以这样做;

...

class Weapon(Item):
    def __init__(self, name, description, value, damage, speed):
        self.damage = damage
        self.speed = speed
        Item.__init__(self, name, description, value)

class Blaster(Weapon):
    def __init__(self, name, description, value, Range, accuracy):
        self.accuracy = accuracy
        self.Range = Range

        blasters_damage = 20
        blasters_speed = 30
        Weapon.__init__(self, name, description, value, blasters_damage , blasters_speed)

blaster = Blaster(
    name="MyBlaster",
    description="A huge weapon",
    value=10,
    Range=50,
    accuracy=0.5
)

...