Python——类操作3——继承1
#class people(object): 新式类 class people: # 经典类 def __init__(self,name,age): self.name=name self.age=age self.friends=[] def eat(self): print("%s is eating..." % self.name) def sleep(self): print("%s is sleeping..." % self.name) def talk(self): print("%s is talking ...." % self.name) # 多继承 class Relation(object): def make_friends(self, obj): print("%s is making friend with %s" % (self.name, obj.name)) self.friends.append(obj) #传obj而不是obj.name ''' 多继承时,继承其中一个即可 ''' class Man(people,Relation): def __init__(self,name,age,sex): people.__init__(self,name,age) #经典类写法 #super(Man,self).__init__(name,age) #用于多继承方便 #新式类写法 self.sex=sex def work(self): print("%s is working...." % self.name) def sleep(self): #重构父类方法 # print("man is sleeping....") 直接覆盖父类 people.sleep(self) print("man is sleeping ....") #输出:先输出父类的sleep()然后再输出子类的sleep() class Woman(people,Relation): def __init__(self,name,age,sex): people.__init__(self,name,age) self.sex=sex def huazhuang(self): print("%s is huazhuang now.." % self.name) m1=Man("Jack",26,"男") m1.eat() m1.work() m1.sleep() w1=Woman("Alice",28,"女") w1.huazhuang() m1.make_friends(w1) w1.name="Back" print(m1.friends[0].name)