Python类属性不继承
我确信一定有我的问题的副本,但还没有找到。我是一个试图最终学习OOP的新手。在以下代码中,我有三个级别的类-子类似乎从基类继承属性,但不是从其直接父类继承属性:Python类属性不继承,python,inheritance,python-2.7,Python,Inheritance,Python 2.7,我确信一定有我的问题的副本,但还没有找到。我是一个试图最终学习OOP的新手。在以下代码中,我有三个级别的类-子类似乎从基类继承属性,但不是从其直接父类继承属性: class Option(object): def __init__(self, *args, **kwargs): self.strike_type = kwargs.get('strike_type') self.multiplier = kwargs.get('mutiplier', 100
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,似乎没有什么区别。这些参数都是从StutPoT转换为选项,但它似乎并不喜欢中间类中的属性。
后续-我无法直接调用put类:
put = Put(strike_type=-1, exp_months=6, strike_steps=2, ratio=2)
TypeError: object.__init__() takes no parameters
如果您能深入了解正在发生的事情,我们将不胜感激。当您使用
super
时,第一个参数应该是进行调用的类,而不是它的超类。所以在Put
中,你应该使用super(Put,self)
,在ShortPut
中,你应该使用super(ShortPut,self)+1——使用super
的要点之一就是:你不必硬编码超类,因此,在mro
可能不明显的地方使用多重继承代码会更容易。我现在就明白了,谢谢。让我大吃一惊的是,我以为自变量指的是它的类,但我现在看到它绑定到一个给定的类实例(就像我说的,我还在学习OOP)。