somepeople

python面向对象—继承&组合

继承:一般出现在子类和父类之间,子类“属于”或者称之为“是”父类,子类具有父类的所有属性

如果没有指定基类,python的类会默认继承object类,object是所有python类的基类,它提供了一些常见方法(如__str__)的实现

组合:对象拥有另一个对象的属性。对象定义一个属性指向另一个对象的内存地址

代码实现:

(继承):

class Creature:
    def __init__(self,name,age):
        self.name = name
        self.age = age


class People(Creature):
    def __init__(self,name,age,sex,work,factory):
        super().__init__(name,age)  #重用父类的属性
        self.sex = sex
        self.work = work
        self.factory = factory

    def job(self):
        print('%s work in %s as a %s'%(self.name,self.factory,self.work))

ryan = People('ryan',28,'man','yw','BZT')
ryan.job()

(组合):

class Company:
    def __init__(self,factory_name,work):
        self.factory_name = factory_name
        self.work = work


class People:
    def __init__(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex

    def job(self,comp):
        print('%s work in %s as %s '%(self.name,comp.factory_name,comp.work))


ryan = People('ryan',28,'man')
BaizhiTong = Company('BZT','yw')
ryan.works = BaizhiTong
print(ryan.works.factory_name)

 

posted on 2020-08-26 02:34  Hello_Thanos  阅读(103)  评论(0编辑  收藏  举报

导航