类的组合

定义一个人的类,人有头、躯干、手、脚等属性,这几个属性又可以是通过一个个类实例化的对象,这就是组合

class Person:
    def __init__(self, id_num, name, hand, foot, trunk, head):
        self.id_num = id.num
        self.name = name
        self.hand = hand
        self.foot = foot
        self.trunk = trunk
        self.head = head


# 担人的手脚等较相似,也可以写成实例
class Hand:
    pass


class Foot:
    pass


class Trunk:
    pass


class Head:
    pass

class Person:
    def __init__(self, id_num, name, hand, foot, trunk, head):
        self.id_num = id_num
        self.name = name
        self.hand = Hand()
        self.foot = Foot()
        self.trunk = Trunk()
        self.head = Head()

#这就是一种组合

具体的例子:

class School:
    def __init__(self, name, addr):
        self.name = name
        self.addr = addr

    def zhao_sheng(self):
        print("%s 正在招生" % self.name)


class Course:
    def __init__(self, name, price, period, school):
        self.name = name
        self.price = price
        self.period = period
        self.school = school


s1 = School("oldboy1", "北京 ")
c1 = Course("Python", 100, "1year", s1)

print(c1.school.name)
#即将对象作为参数传入另一个对象
class School:
    def __init__(self, name, addr):
        self.name = name
        self.addr = addr

    def zhao_sheng(self):
        print("%s 正在招生" % self.name)


class Course:
    def __init__(self, name, price, period, school):
        self.name = name
        self.price = price
        self.period = period
        self.school = school


s1 = School("oldboy1", "北京 ")
c1 = Course("Python", 100, "1year", s1)
c2 = Course("Linux", 1000, "1.2year", s1)
print(c1.school.name)

更Low的解决方式,定义一个类中的列表,放入其他对象:

class School:
    def __init__(self, name, addr):
        self.name = name
        self.addr = addr
        self.Course_List = []

    def zhao_sheng(self):
        print("%s 正在招生" % self.name)


class Course:
    def __init__(self, name, price, period, school):
        self.name = name
        self.price = price
        self.period = period
        self.school = school


s1 = School("oldboy1", "北京 ")
c1 = Course("Python", 100, "1year", s1)
c2 = Course("Linux", 1000, "1.2year", s1)
s1.Course_List.append(c1)
s1.Course_List.append(c2)
for course_obj in s1.Course_List:
    print(course_obj.name)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值