【问题标题】:Python class attributes not inheritingPython类属性不继承
【发布时间】:2013-09-02 05:37:41
【问题描述】:

我确定我的问题一定有重复,但没有找到。我是一个试图最终学习 OOP 的新手。在下面的代码中,我有三个级别的类 - 子类似乎是从基类继承属性,而不是从其直接父类继承属性:

class Option(object):
    def __init__(self, *args, **kwargs):
        self.strike_type = kwargs.get('strike_type')
        self.multiplier = kwargs.get('mutiplier', 100)
        self.exp_months = kwargs.get('exp_months', 1)
        self.strike_steps = kwargs.get('strike_steps', 1)


class Put(Option):
    def __init__(self, *args, **kwargs):
        super(Option, self).__init__(*args, **kwargs)
        self.option_type = 'put'


class ShortPut(Put):
    def __init__(self, *args, **kwargs):
        super(Put, self).__init__(*args, **kwargs)
        self.ratio = kwargs.pop('ratio', 1)
        self.qty_mult = -1


shortput = ShortPut(strike_type=-1, exp_months=6, strike_steps=2, ratio=2)

shortput.ratio #class ShortPut
2

shortput.exp_months #class Option
6

shortput.option_type #class Put
AttributeError: 'ShortPut' object has no attribute 'option_type'

dir(shortput) #dunder entries removed
['exp_months',
'multiplier',
'qty_mult',
'ratio',
'strike_steps',
'strike_type']

因此,如果我将其剪切并粘贴到 Option 或 ShortPut 中,该属性就可以正常工作。我也尝试过更改 init 模块中的顺序,但如果在其他属性之前或之后调用 super 似乎并没有什么不同。论据从 ShortPut 流向 Put 到 Option,但似乎不喜欢中产阶级的属性。

后续 - 我不能直接调用 put 类:

put = Put(strike_type=-1, exp_months=6, strike_steps=2, ratio=2)
TypeError: object.__init__() takes no parameters

任何对正在发生的事情的见解将不胜感激。

【问题讨论】:

    标签: python inheritance python-2.7


    【解决方案1】:

    当您使用super 时,第一个参数应该是您从中进行调用的类,而不是它的超类。所以在Put 你应该使用super(Put, self) 而在ShortPut 你应该使用super(ShortPut, self)

    【讨论】:

    • +1 -- 使用super 的要点之一就是:您不必对超类进行硬编码,从而更容易使用mro 的多重继承代码可能不明显。
    • 我现在明白了,谢谢。让我感到困惑的是,我认为 self 参数指的是它的类,但我现在看到它绑定到给定的类实例(就像我说我还在学习 OOP)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 2012-07-25
    • 2015-03-27
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多