python 2 和3 区别之一

本文通过一个简单的示例对比了Python2与Python3中多重继承的不同行为,并介绍了如何在Python2中实现与Python3相同的多重继承效果。
class classmate:
    def __init__(self,name):
        self.name = name

    def eat(self):
        print ('%s is eating.'%self.name)

    def drink(self):
        print ('%s is drinking'%self.name)

class female(classmate):

    def drink(self):
        print ('%s drink orange juice'%self.name)

class male(classmate):

    def drink(self):
        print ('%s drink alcohol'%self.name)

class pythoner(classmate):

    def occupation(self):
        print ('%s is a pythoner.'%self.name)



class fe_pythoner(pythoner,female):
    pass
class male_pythoner(pythoner,male):
    pass

eva = fe_pythoner('eva')
eva.drink()

sweet = male_pythoner('sweet')
sweet.drink()

对于这段代码若是python2输出为

eva is drinking
sweet is drinking

 

若是python3 输出为

eva drink orange juice
sweet drink alcohol

 

python2 中若要输出出相同的结果要将首行改为class classmate(object)或

 

class fe_pythoner(pythoner,female):
pass
class male_pythoner(pythoner,male):
pass

改成

class fe_pythoner(female,pythoner):
pass
class male_pythoner(male,pythoner):
pass

 

 

 

所以写成标准形式class classmate(object):是一个好习惯。

python2 默认深度优先

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值