python - 子类如何在python中继承父类的属性

标签 python inheritance attributes init super

据我所知,在 OO 中,子类继承其父类的所有属性。但在 python 中,子类不会继承父类的属性,直到它以这种方式调用父类的 init 方法: super().初始化() . 我想知道我的推论是否正确?为什么会这样?我猜它是其他语言,如 java,子类会自动继承其父类的所有属性,而无需执行此类操作。 提前谢谢你。

最佳答案

当您在子类中调用 super().__init__() 时,您只是在执行父类的 init 方法以及该方法中的所有内容。

子类将继承属性和所有方法,而无需调用super().__init__() 函数。但是,如果您在子类中定义了一个 init 函数,那么它将覆盖子类中复制的父类 init 方法。您必须记住,当子类继承父类时,它本质上是创建了一个子类,该子类是父类的副本,可以在不影响父类的情况下添加和/或更改子类。您可以选择希望子类从父类继承哪些内容而不覆盖它们,也可以选择您不想通过覆盖继承哪些内容。

示例 1

class parentclass:
        b = 31

        def __init__(self):
                self.a = 21
        def add(self, a, b):
                c = a+b
                print(c)


class childclass(parentclass):
        pass

child1 = childclass()

child1.add(10,20)
print(child1.b)
print(child1.a)

输出:

30
31
21

示例 2:


class parentclass:
        b = 31

        def __init__(self):
                self.a = 21
        def add(self, a, b):
                c = a+b
                print(c)


class childclass(parentclass):
        def __init__(self):
                self.name="child"

child1 = childclass()

child1.add(10,20)
print(child1.b)
print(child1.a)

输出:

Traceback (most recent call last):
  File "C:/Users/chees/PycharmProjects/untitled/idk.py", line 20, in <module>
    print(child1.a)
AttributeError: 'childclass' object has no attribute 'a'
30
31

编辑:

这就是为什么在 child 的 init 方法中需要 super().init() 方法,以便在 child 的 init 方法中再次复制父 init 方法,即:


class parentclass:
        b = 31

        def __init__(self):
                self.a = 21
        def add(self, a, b):
                c = a+b
                print(c)


class childclass(parentclass):


        def __init__(self):
                super().__init__()
                self.name="child"

child1 = childclass()

child1.add(10,20)
print(child1.b)
print(child1.a)

相同
class parentclass:
        b = 31

        def __init__(self):
                self.a = 21
        def add(self, a, b):
                c = a+b
                print(c)


class childclass(parentclass):


        def __init__(self):
                self.a = 21
                self.name="child"

child1 = childclass()

child1.add(10,20)
print(child1.b)
print(child1.a)

关于python - 子类如何在python中继承父类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62976649/

相关文章:

python - 有人可以向我解释一些简单的 python 概念吗?

ruby - 为什么 inspect for the subclasses of built-in classes 中没有列出实例变量?

c++ - 如何将 lambda 的 operator() 声明为 noreturn?

c++ - 成员函数指针和继承

c# - 属性如何继承?

c# - 在 C# 中,属性可以应用于静态类、方法或属性吗?

python - 当尝试使用 pythonnet 从脚本构建 exe 时,py2exe 失败并显示 "No module named ' clr'"

python - 从文件加载特定的 PyYAML 文档

python - 从 BigQuery 查询到 Jupyter 时出现 "' NotebookFormatter ' object has no attribute ' get_result '"错误?

C# 泛型和泛型约束