【发布时间】:2019-05-16 08:03:10
【问题描述】:
我想在我的子类中继承一个属性,但我想从超类中调用一个方法。
然而,为了从父级继承属性,我需要调用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 将不允许我使用该属性。如何覆盖子类中的属性,但维护超类的方法?
【问题讨论】:
-
在超类中:self.attribute = getattr(self, attribute, None) 或 4。如果它被设置在子类中,它不会改变它,否则它设置为 4。对于像 0 这样的虚假值可能会有点棘手。
-
先调用 super().__init__。
标签: python python-2.7 oop