zoukankan      html  css  js  c++  java
  • python3.6 子类的__init__调用父类的__init__

    python3.6 子类的__init__调用父类的__init__

    父类

    class worker:
        def __init__(self):
            self.a=1
            self.b=2
    
    
    if __name__=="__main__":
        worker()

    子类

    from test.test02 import worker
    
    class workertet(worker):
        def __init__(self):
            worker.__init__(self)
            c = 3
            d = 4
            print(self.a)
            print(self.b)
            print(c)
            print(d)
    
        def test(self):
            print(self.a)
            print(self.b)
    
    
    if __name__=="__main__":
        workertet()

    输出:

    C:Userslys-tbcAppDataLocalProgramsPythonPython36python.exe D:/pythonwakce/mysqltest/test/test03-init.py
    1
    2
    3
    4

    Process finished with exit code 0

    如此设计的原因是,在子类中需要获得超类的成员和方法,而通过在子类的__init__方法中调用超类的__init__方法,并手动给它传递指向子类的self值,可以使超类的__init__方法将所初始化的变量设置成子类的变量,这样,就可以在子类中直接访问超类的变量了

  • 相关阅读:
    053592
    053591
    053590
    053589
    053588
    053676
    C# WPF Border控件总结
    Android Studio 添加jar或aar依赖的两种方式
    javascript Date与string之间的转换
    C#:使用dsoframer.ocx控件实现内嵌office效果(详解)
  • 原文地址:https://www.cnblogs.com/lystbc/p/8424586.html
Copyright © 2011-2022 走看看