python 类继承

python2中类分为两种 新式类、经典类

//新式类
class A(object):
    pass
//经典类
class A:
    pass

python3中两种写法都是新式类

1.新式类与经典类 MRO算法不同

        经典类:深度优先遍历

        新式类:广度优先遍历

2.新式类相同父类只执行一次构造函数,经典类重复执行多次。

类的继承分单继承和多继承

class A(object):
    def __init__(self, content):
       self.content = content 
    def Asay(self):
        print(self.content)
class B(object):
    def __init__(self, content):
       self.content = content 
    def Bsay(self):
        print('Bsay'+self.content)
//单继承
class C(A):
    pass
//多继承
class D(A,B):
    pass

创建实例

​
class A(object):
    def __init__(self, content):
       self.content = content 
    def Asay(self):
        print(self.content)
class B(object):
    def __init__(self, content):
       self.content = content 
    def Bsay(self):
        print('Bsay'+self.content)

//多继承
class D(A,B):
    def Dsay():
        print('Dsay')
        
class E(A,B):
    def __init__(self, content):
        self.content = content

​d = D('dhellow')
e = E('ehellow')
d.Asay()// 此时输出dhellow 因为d类没有构造函数,会通过mro进行遍历父类找到A的构造函数
e.Asay()// 此时输出ehellow e类构造函数被执行,但是A类的构造没有执行,但是绑定到的self是e执行方法时会调用self.content的值

//B虽然遍历排在A后面,但是如果B中有和A相同属性或方法时会把A覆盖

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值