经典类和新式类的区别
在python2中,如果明确写了继承object,那么这个类就是新式类;如果没有写,那么就是旧式类(经典类)。
在python3中,不管写没写object,这个类都是新式类。
1)首先,写法不一样:
class A: #经典类写法
pass
class B(object): #新式类写法
pass
2)多继承中,新式类采用广度优先搜索,而旧式类是采用深度优先搜索,python3中全是广度查询
3)在继承中新式类和经典类写法区别
SchoolMember.__init__(self,name,age,sex) #经典类写法
super(Teacher,self).__init__(name,age,sex) #新式类写法

代码如下
class D:
def talk(self):
print('D')
class B(D):
pass
# def talk(self):
# print('B')
class C(D):
pass
def talk(self):
print('C')
class A(B,C):
pass
# def talk(self):
# print('A')
a = A()
a.talk()
2、重写特殊的构造方法
1. 注:如果一个类的构造方法被重写,那么就需要调用超类的构造方法,否则对象可能不能给被正确的初始化
2. 其实调用超类构造方法很容易,SongBird类中只添加一行代码
经典类写法: Bird.init(self)
新式类写法: super(SongBird,self).init()
3. 如果将下面代码没有2中的那句调用父类Bird中的self.hungry方法会报错
if self.hungry == True:
AttributeError: SongBird instance has no attribute 'hungry'
新式类,经典类,无超类构造方法报错
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry == True:
print("Aaaah...")
self.hungry = False
else:
print("no, thanks")
a = Bird()
a.eat()
a.eat()
class SongBird(Bird):
def __init__(self):
# Bird.__init__(self) # 经典类写法
# super(SongBird,self).__init__() # 新式类写法
self.sound = 'Squawk'
def sing(self):
print(self.sound)
b = SongBird()
b.sing()
b.eat()
本文详细解析了Python中经典类与新式类的区别,包括写法、多继承中的搜索策略及特殊构造方法的重写技巧。适用于Python2与Python3开发者,帮助理解类的继承与初始化机制。

319

被折叠的 条评论
为什么被折叠?



