我想在我的子类中继承一个属性,但我想从超类中调用一个方法。你知道吗
但是,为了从父级继承属性,我需要对其调用super
。但是当我对它调用super
时,它会从超类而不是子类中为它提供属性。如何确保它获得我在定义子类时分配给它的属性?你知道吗
class SuperClass2(object):
def __init__(self, passed_in):
self.attribute = 4
self.passed_in = passed_in
self.shared_method()
def shared_method(self):
assert self.passed_in == self.attribute, ' sorry they are not equal '
class SubClass2(SuperClass2):
def __init__(self, passed_in):
self.attribute = 3 # i set attribute to 3 here
self.passed_in = passed_in
super(SubClass2, self).__init__(passed_in) # I already set attribute to 3 ....but gets overwritten when I call super
在上面的例子中,child=SubClass2(3)
产生AssertionError: sorry they are not equal
。你知道吗
正如您在上面的示例中所看到的,它将不允许我通过将属性设置为3来定义属性。如何重写子类中的属性,但维护超类的方法?你知道吗
方法1
最明显的是先调用
super()
,然后修改属性方法2
始终将这些公共属性委托给超类,因此如下所示:
方法3
将初始化委托给一个单独的方法,然后在子类中重写该方法
相关问题 更多 >
编程相关推荐