如何重写父类?

2024-03-28 13:09:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个班:

class Parent(object):
    def __init__(self):
        self.a = 0
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.a = 1

print(Child().b)

输出是10+1),但我希望有21+1)。我怎样才能达到这样的效果?你知道吗


Tags: selfchildobjectinitdefclassparentprint
2条回答

Parent.__init__之外分配a属性:

class Parent(object):
    a = 0
    def __init__(self):
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        self.a = 1
        super().__init__()

print(Child().b)

如果未提供参数,则可以使用key word argument在父类中设置a的值:

class Parent(object):
    def __init__(self, a=None):
        if a is None:
            self.a = 0
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        self.a = 1
        super().__init__(self.a)

parent = Parent()
child = Child()
print(parent.a, parent.b) 
print(child.a, child.b)

输出:

0 1
1 2

另一种方法可以使用类变量

class Parent(object):
    a = 0
    def __init__(self):
        self.a = self.__class__.a
        self.b = self.a + 1

class Child(Parent):
    a = 1
    def __init__(self):
        super().__init__()

parent = Parent()
child = Child()
print(parent.a, parent.b) 
print(child.a, child.b)

输出:

0 1
1 2

在上面的例子中,使用类变量,您可以完全不用子类中的__init__方法:(这可能适用于,也可能不适用于您的实际用例)

class Parent(object):
    a = 0
    def __init__(self):
        self.a = self.__class__.a
        self.b = self.a + 1

class Child(Parent):
    a = 1

相关问题 更多 >