【问题标题】:Learning inheritance | TypeError: __init__() takes 3 positional arguments but 5 were given [duplicate]学习继承 | TypeError:__init__() 采用 3 个位置参数,但给出了 5 个 [重复]
【发布时间】:2020-07-18 17:14:37
【问题描述】:

试图从超类 BasicToken 继承到子类 StableCoin

supply 的值没有被 子类继承:StableCoin

谁能解释一下原因?

class BasicToken:

    asset_class = "Crypto-Currency"

    def __init__(self, symbol):
        self.symbol = symbol


class StableCoin(BasicToken):
    def __init__(self, color, supply):
        self.color = color
        self.supply = supply

icon = BasicToken('icx')
icxStable = StableCoin('DMM', ['Blue', 'White'])

print('Icon Symbol: '+ icon.symbol)
print('IcxStable Symbol: '+ icxStable.symbol)

Error:

Traceback (most recent call last):
  File "C:/Users/Samson/Documents/PythonCourse-master/Section_04/assignment_04.py", line 30, in <module>
    print('IcxStable Symbol: '+ icxStable.symbol)
AttributeError: 'StableCoin' object has no attribute 'symbol'

【问题讨论】:

  • 你需要在子类的构造函数中调用超类的构造函数。 super()

标签: python python-3.x inheritance


【解决方案1】:

将以下内容添加到稳定币的初始化中

class StableCoin(BasicToken):
    def __init__(self, symbol, color, supply):
        super(StableCoin, self).__init__(symbol)
        self.color = color
        self.supply = supply

如果你使用的是 PY3,调用 super 更容易super().__init__(symbol)。虽然上面也可以。

谈到你的方法,你的理解似乎有点不正确。 icon 是 BasicToken 的一个实例,而 icxStable 是一个单独的对象,它是 StableCoin 的一个实例。它们不相关。

例如,假设我们有一个类 Mammal 具有属性 age,另一个类 Human(Mammal) 具有附加属性“height”,这就像构造 blue_whale_whaley=Mammal(age=4)chuck_norris=Human(height=180) 然后了解chuck_norris.age 是 blue_whale.age ,这不是因为它们是 2 个不同的对象。正确构造chuck_norris 是chuck_norris=Human(age=50, height=180)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2019-05-16
    • 2020-09-25
    • 2018-06-21
    • 1970-01-01
    相关资源
    最近更新 更多