对象的组合又叫嵌套或建模,是通过不同类之间的对象相互赋值完成的,具体如下面的例子
class School(): def __init__(self,name,addr): self.name=name self.addr=addr def speech(self): pass sch1=School("北京","昌平区沙河") sch2=School("上海","景宁区") sch3=School("深圳","某某区") class Student(): def __init__(self,name,age,salary): self.name=name self.age=age self.__slary=salary stu1=Student("刘能",‘22‘,12000) stu2=Student("张一山",‘25‘,13000) stu3=Student("赵本山",‘55‘,50000) stu4=Student("刘德华",‘55‘,60000) #下面通过实例的赋值进行嵌套 # ############## 老师分配校区 stu1.school=sch1 stu2.school=sch2 stu3.school=sch3 stu4.school=sch3 print(stu1.school.name) #因为已经完成了嵌套,stu1.school有了School类实例的特性 print(stu1.school.addr) print(stu1.school.speech())
原文地址:https://www.cnblogs.com/zhuhaofeng/p/9571339.html
时间: 2024-11-03 22:35:17