python - 在 Python 3 中调用 super() 之前覆盖父类属性

标签 python class python-3.x inheritance attributes

考虑以下示例。 Parent 类有一个名为 attr 的属性。 Child1Child2 都有一个同名的属性。 Child1Child2 之间的唯一区别是 Child1 在覆盖父级的 attr 之前调用 super() 属性。 Child2 似乎并没有覆盖父级的 attr,因为该属性是在 super() 调用之前定义的。 Child2 在调用 super() 之前定义父级的 attr 时,有没有办法覆盖它?

class Parent():

    def __init__(self):
        self.attr = "parent"

class Child1(Parent):

    def __init__(self):
        super().__init__()
        self.attr = "child1"

class Child2(Parent):

    def __init__(self):
        self.attr = "child2"
        super().__init__()

if __name__ == '__main__':
    child1 = Child1()
    print(child1.attr) # "child1"

    child2 = Child2()
    print(child2.attr) # "parent"

最佳答案

没有“ parent 的attr“ child 的attr这样的东西。该实例只有一个 attr,无论它是从父类中的代码设置的,还是从子类中的代码中设置的,还是从没有类的代码中设置的。

换句话说,这些例子产生相同的结果:

例子1

class A:
    def __init__(self):
        self.attr = 1

class B(A):
    pass

b = B()

例子2

class A:
    pass

class B(A):
    def __init__(self):
        self.attr = 1

b = B()

示例 3

class A:
    pass

class B(A):
    pass

b = B()
b.attr = 1

实际答案;)

因此,Child1Child2 之间的区别在于 Child1__init__ 执行此操作:

    self.attr = "parent"
    self.attr = "child1"

Child2__init__ 有效地做到了这一点:

    self.attr = "child2"
    self.attr = "parent"

关于python - 在 Python 3 中调用 super() 之前覆盖父类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40195257/

相关文章:

python - 使用 django 处理数据库迁移/升级

iOS isKindOfClass 和 isMemberOfClass 的区别

python - 如何在python中调用另一个文件中的函数

python-3.x - 如何将最新 (2020) Django 安装到 AWS EC2 Linux 2 实例并使用 Apache Hello World 服务

Python RC4实现错误 'range'对象不支持项赋值

python - 将字符串时间戳转换为 Python 日期时间(原为 : how to properly convert char into float or double in Python)

python - Unicode解码错误: 'ascii' codec can't decode byte 0xe2 in position 4: ordinal not in range(128)

python - 如何在不使用python替换方法的情况下替换句子中的单词

c++ - (为什么)我们可以在初始化时将非静态类成员分配给静态变量吗?

python - ValueError : shapes (20, 14) 和 (13,1) 未对齐 : 14 (dim 1) ! = 13(暗淡 0)