面向对象--组合

在面向对象里,组合的概念:  两个相互关联的类, 其中一个类的对象 作为另一个类的对象的属性.

               此时,我们说 产生了 组合. 

                                    例如: 人 和 武器 ;  学生 和 课程 ; 圆形 与 圆环.

示例代码如下:

class Student:
    def __init__(self,name,age,course):
        self.name = name
        self.age = age
        self.course = course   # 这里发生了 组合 : self.course = python

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

python = Course('python',20000,'6 months')  # python是一个课程对象
a = Student('a',30,python)

print(a.course.name)
print(a.course.price)
Student类的course属性 是python对象
学生的课程属性 和 python对象组合了
可以通过学生 找到python 可以通过python找到python课程的名字、价格、周期

其实,不只是例子中,这种我们自定义的类有组合.
在如上例子中,我们可以通过 a.name 拿到字符串 'a', 那对这个字符串来说, 它就是一个str类的对象, 它又可以有 'a'.strip() 等等的字符串操作.
即 a.name.strip()  这就是我们自定义的Student类 与 str类 产生了组合.



猜你喜欢

转载自www.cnblogs.com/LL97155472/p/10607971.html