类的继承1
1.子类可以继承父类的方法:
class People:
def __init__(self,name,age):
self.name=name
self.age=age
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 Man(People):
def smoke(self):
print("%s is smoking..."%self.name)
m1=Man("Jack",18)
m1.eat()
m1.smoke()
运行结果:
Jack is eating.. Jack is smoking...
2.在子类中给父类方法增加新功能。
class People:
def __init__(self,name,age):
self.name=name
self.age=age
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 Man(People):
def smoke(self):
print("%s is smoking..."%self.name)
def sleep(self):
People.sleep(self)
print("子类也在睡觉")
m1=Man("Jack",18)
m1.sleep()
运行结果如下:相当于给父类的方法增加了新功能。
Jack is sleeping.. 子类也在睡觉
3.子类之间的方法不能相互调用,women是不能调用man下面的smoke方法的。
class People: def __init__(self,name,age): self.name=name self.age=age 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 Man(People): def smoke(self): print("%s is smoking..."%self.name) def sleep(self): People.sleep(self) print("子类也在睡觉") m1=Man("Jack",18) m1.sleep() class Woman(People): def shop(self): print("%s is shopping"%self.name) w1=Woman("Lily",26) w1.shop()
4.子类中的man可以多传一个参数,同时不要影响women的正常运行。
#class People: #经典写法
class People(object): #新式写法 def __init__(self,name,age): self.name=name self.age=age 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 Man(People): def __init__(self,name,age,money): People.__init__(self,name,age) #super(Man,self).__init__(name,age) #新式写法 self.money=money print("%s有%s钱。。"%(self.name,self.money)) def smoke(self): print("%s is smoking..."%self.name) def sleep(self): People.sleep(self) print("子类也在睡觉") m1=Man("Jack",18,10000) class Woman(People): def shop(self): print("%s is shopping"%self.name) w1=Woman("Lily",26) w1.shop()
运行结果
Jack有10000钱。。 Lily is shopping
5.多继承,可以同时继承多个父类:
class People: def __init__(self,name,age): self.name=name self.age=age 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 Relation(object): def make_friends(self,obj): print("%s is making friend with %s"%(self.name,obj.name)) class Man(People,Relation): def __init__(self,name,age,money): People.__init__(self,name,age) self.money=money print("%s有%s钱。。"%(self.name,self.money)) def smoke(self): print("%s is smoking..."%self.name) def sleep(self): People.sleep(self) print("子类也在睡觉") class Woman(People,Relation): def shop(self): print("%s is shopping"%self.name) m1=Man("Jack",22,10000) w1=Woman("Lily",18) m1.make_friends(w1)
运行结果:
Jack有10000钱。。 Jack is making friend with Lily
6.多继承的时候,父类是从左到右执行的。class Woman(People,Relation), 先执行People,再执行 Relation