python_97_类的继承2
# 经典类与新式类差别主要体现在多继承上
#多继承是从左到有
class People():#经典类
#class People(object):#新式类
def __init__(self,name,age):
self.Name=name
self.Age=age
self.friends=[]
def eat(self):
print('%s is eating'%self.Name)
def talk(self):
print('%s is talking'%self.Name)
def sleep(self):
print('%s is sleeping'%self.Name)
class Relationship(object):
def make_friends(self,friend):
print('%s is naking friends with %s'%(self.Name,friend.Name))
self.friends.append(friend)#括号内不能写friend.Name(只是一个字符串),比如改名之后将不顶用,还是以前的名字
class bianxinren(People):#继承
pass#可以什么也不做,之继承
m1=bianxinren('变性人','20')
m1.eat()
class Man(People):#继承
def piao(self):
print('%s is piaoing...20s...done'%self.Name)
def sleep(self):#给父类方法增加新功能
People.sleep(self)#不加此语句,将覆盖父类的sleep
print('%s 睡的时间长'%self.Name)
m2=Man('男人','20')
m2.piao()
m2.sleep()
class Woman(People,Relationship):#从左到有,先继承People,再继承Relationship
def __init__(self,name,age,type_breast):#重构参数,对构造函数进行重构
#People.__init__(self,name,age)#经典类调用父类,如果有两个父类,需要写两次此代码,用super就不用写两遍,如下
#Relationship.__init__(self,good)假设Relationship.__init__有good
#可将上一步改为self.relationgship=Relationship(self,good),此步属于组合
super(Woman,self).__init__(name,age)#新式类调用父类的另一种方法,此方法更方便
self.type_breast=type_breast
print('%s的罩杯:%s'%(self.Name,self.type_breast))
def born(self):
print('%s is born a baby'%self.Name)
m3=Woman('女人','25','C')
m3.born()
# m3.piao()不能执行,是别的子类的方法
m3.make_friends(m2)
m3.Name='好女人'
print(m3.friends[0].Name)
在python2中经典类是按照深度优先进行继承的,新式类是按照广度优先来进行继承的
在python3中经典类和新式类均是按照广度优先来继承的

参考:http://www.cnblogs.com/alex3714/articles/5188179.html

浙公网安备 33010602011771号