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:\Users\lys-tbc\AppData\Local\Programs\Python\Python36\python.exe D:/pythonwakce/mysqltest/test/test03-init.py
1
2
3
4

Process finished with exit code 0

 

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

posted @ 2018-02-06 22:42  糖宝虫  阅读(309)  评论(0编辑  收藏  举报