python面向对象-继承

#!/usr/local/bin/python3
# -*- coding:utf-8 -*-

# class People: #经典类
class People(object): #新式类,此处的object是基类,People继承object
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.makeFriends = []

    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 friends with %s" % (self.name, obj.name))
        self.makeFriends.append(obj)


class Man(People, Relation):  # 多继承父类People, Relation
    def __init__(self, name, age, money): # 子类中添加新的属性
        # 经典类写法:People.__init__(self, name, age)
        super(Man, self).__init__(name, age)    # 注意:此处要先调用父类的__init__方法
        self.money = money
        print("%s 一出生就有%s money" % (self.name, self.money) )

    def piao(self):
        print("%s is piaoing..20h...down" % self.name)

    def sleep(self):    # 重构父类方法
        super(Man, self).sleep()    # 先加载父类的方法,等同与 People.sleep(self)
        print("wo is sleeping...")  # 然后添加新功能

class Woman(People, Relation):    # 多继承父类People, Relation
    def birth(self):
        print("%s is born a baby..." % self.name)

m1 = Man("zhangyu", 25, 10)
# m1.eat()
# m1.piao()
# m1.sleep()

w1 = Woman("mahongyan", 25)
# w1.birth()

m1.make_friends(w1)
print(m1.makeFriends[0].name)

  

猜你喜欢

转载自www.cnblogs.com/octopuszy/p/9064711.html