一。面向对象super的作用:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class parent(object): def __init__(self): self.test() def test(self): print('parent---') class BaseHandler(object): def test(self): print('BASEhandler') super(BaseHandler,self).test() #不影响后面函数运行,即运行自身的test函数,也运行别人的。如果不加super的话运行自身后停止运行后面相同的函数名(如果父类和子类都有相同的方法,先运行父类的再运行子类的) class task(BaseHandler,parent): pass obj=task()
运行结果:
BASEhandler
parent---
不加super后:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class parent(object): def __init__(self): self.test() def test(self): print('parent---') class BaseHandler(object): def test(self): print('BASEhandler') class task(BaseHandler,parent): pass obj=task()
运行结果:
BASEhandler
二。函数继承后self的变化
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Bbh: def server(self): self.sz() def sz(self): self.xiaowen() def process_request(self): print('yun') class Mr(Bbh): def sz(self): print('sz') def xiaowen(self): self.process_request() class Yun: def process_request(self): print('yun') class Zzc(Yun,Mr): pass obj=Zzc() obj.server() #运行结果: sz
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Bbh: def server(self): self.sz() def sz(self): self.xiaowen() def process_request(self): print('yun') class Mr(Bbh): def sz(self): print('sz') def xiaowen(self): self.process_request() def hello(self): print(self) self.test() def test(self): print('yun') class Yun(Mr): def process_request(self): print('yun') def test(self): print('yun') class Zzc(Yun): pass obj=Zzc() obj.hello()
1.obj=Zzc() #self=Zzc
2.obj.hello() #Zzc中执行hello方法
3.Zzc中无hello方法,在父类Yun中寻找hello方法。
4.类Yun中无hello方法,在父类Mr类中继续寻找
5.Mr中找到hello方法执行 ,hello方法中执行了self.test()方法,在self(Zzc)中再次寻找test方法
6.Zzc中无test方法,在父类Yun中寻找
7.Yun中找到test方法并执行,执行结果等于“yun"
总结:函数被谁实例化self就会一直等于谁,无论多少层继承关系,self的值始终不变。函数被实例化时首先执行__init__方法,如果类中无init方法那么就执行父类的init方法。如果执行的方法类中没有,就会一层一层网上找。(python3广度优先,python2深度优先)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class test: def hello(self): print('test--------') class Mr(test): pass class Yun(Mr): pass class Bbh(test): def hello(self): print('Bbh') class Zzc(Yun,Bbh): pass obj=Zzc() obj.hello()
结果Bbh(广度优先)
注意:
#两个父类都必须还继承别的类,否则会成为深度优先
如:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class test: def hello(self): print('test--------') class Mr(test): pass class Yun(Mr): pass class Bbh: def hello(self): print('Bbh') class Zzc(Yun,Bbh): pass obj=Zzc() obj.hello()
运行结果:test--------
class test:
name="test"
def __init__(self):
self.age=23
self.city='bz'
def run(self):
print(self.__dict__) #将init中的变量以字典形式列出来
print(test.name) #访问类变量,及时没有实例化也可以访问,但是实例变量必须要实例化后才能访问,或者会报错
obj=test()
obj.run()