定义一个人的类,人有头、躯干、手、脚等属性,这几个属性又可以是通过一个个类实例化的对象,这就是组合
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)