旧类以调用未绑定的超类构造方法
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 !'
可是假设自己类里有写了构造函数,(戴佳告诉我python里哪怕在同一个类里也没有重载这一说),这里子类覆盖了父类的构造方法。也就没有‘__hungry’这个东西了。所以旧类採用的是在子类的构造函数里以自身作为參数调用父类的__init__。
old_dog = OldDog() old_dog.eat() old_dog.eat() old_wolf = OldWolf() old_wolf.eat() old_wolf.eat()
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是有多重继承的,有些语言不同意多重继承。