python - Python中的继承和init方法

标签 python inheritance init

我是 python 的初学者。我无法理解继承和 __init__()

class Num:
    def __init__(self,num):
        self.n1 = num

class Num2(Num):
    def show(self):
        print self.n1

mynumber = Num2(8)
mynumber.show()

结果:8

没关系。但我将 Num2 替换为

class Num2(Num):
    def __init__(self,num):
        self.n2 = num*2
    def show(self):
        print self.n1,self.n2

结果:错误。 Num2 没有属性“n1”。

在这种情况下,Num2如何访问n1

最佳答案

在第一种情况下,Num2正在扩展类(class) Num并且由于您没有重新定义名为 __init__() 的特殊方法在 Num2 , 它继承自 Num .

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.

在第二种情况下,由于您正在重新定义 __init__()Num2如果要扩展其行为,则需要显式调用父类(super class) ( Num ) 中的那个。

class Num2(Num):
    def __init__(self,num):
        Num.__init__(self,num)
        self.n2 = num*2

关于python - Python中的继承和init方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5166473/

相关文章:

python - kivy 访问 child ID

python - 在继承的 ctypes.Structure 类的构造函数中调用 from_buffer_copy

kotlin - kotlin,该函数在基类的init block 中调用

java - 按钮在扩展 JButton 时不执行任何操作,但它通过返回 JButton 的方法来执行此操作

java - java中的简单继承

git - 重新初始化 c :/xampp/htdocs/website/. git/中现有的 Git 存储库

flutter - Flutter 中的 initState 和 super.initState 是什么?

python - 多处理 Pool.map 的奇怪行为

python - Django 数据库错误 : could not identify an equality operator for type json when trying to annotate a model with jsonfield

python - 如何在 python matplotlib 中使用 set_position 方法来固定坐标轴位置?