python3面向对象注意事项

一。面向对象super的作用:
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()
View Code
运行结果:

BASEhandler
parent---

不加super后:

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()
View Code
运行结果:

BASEhandler

二。函数继承后self的变化

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
View Code
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()
View Code

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深度优先

猜你喜欢

转载自www.cnblogs.com/dufeixiang/p/10199072.html
今日推荐