旧类以调用未绑定的超类构造方法
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 !'
old_dog = OldDog() old_dog.eat() old_dog.eat() old_wolf = OldWolf() old_wolf.eat() old_wolf.eat()
而新类里采用的是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是有多重继承的,有些语言不允许多重继承。
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/xiaopangxia/article/details/46942931