zoukankan      html  css  js  c++  java
  • python学习笔记——旧类与新类继承中的构造函数

    旧类以调用未绑定的超类构造方法

    class OldDog:
        def __init__(self):
            print 'I am a  old dog !'
            self.__hungry = True
    
        def eat(self):
            if self.__hungry:
                print 'I eat it !'
                self.__hungry = False
            else:
                print 'No thanks!'
    
    
    class OldWolf(OldDog):
        def __init__(self):
            OldDog.__init__(self)
            print 'Not only a dog but a wolf !'
    


    Oldwolf类假设不写构造函数,事实上会自己主动继承父类的全部属性和方法。

    可是假设自己类里有写了构造函数,(戴佳告诉我python里哪怕在同一个类里也没有重载这一说),这里子类覆盖了父类的构造方法。也就没有‘__hungry’这个东西了。所以旧类採用的是在子类的构造函数里以自身作为參数调用父类的__init__。


    old_dog = OldDog()
    old_dog.eat()
    old_dog.eat()
    old_wolf = OldWolf()
    old_wolf.eat()
    old_wolf.eat()


    I am a  old dog !
    I eat it !
    No thanks!
    I am a  old dog !
    Not only a dog but a wolf !
    I eat it !
    No thanks!


    Process finished with exit code 0




    而新类里採用的是super函数,新类的写法要么继承自object,要么__mataclass__=type


    class NewDog(object):
        def __init__(self):
            print 'I am a  new dog !'
            self.__hungry = True
    
        def eat(self):
            if self.__hungry:
                print 'I eat it !'
                self.__hungry = False
            else:
                print 'No thanks!'
    
    
    class NewWolf(NewDog):
        def __init__(self):
            super(NewDog, self).__init__()
            print 'Not only a dog but a wolf !'


    新类用super函数给我的直观感受就是好像在写新类是不用一个个道出父类的名字,书上说他的优点是假设继承自多个类的话仅仅要写一次super就搞定了。而不用吧每一个的构造函数都写一遍,当python是有多重继承的,有些语言不同意多重继承。


  • 相关阅读:
    GUI编程
    Markdown学习
    [python3]正则表达式
    python3_json&pickle
    python3_module_sys
    python3_module_os
    Python3_module_random
    Pyhton3_module_time()
    Python3 正则表达式 Regular Expression
    Python循环对象
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/7147546.html
Copyright © 2011-2022 走看看