zoukankan      html  css  js  c++  java
  • 面向对象——组合

    什么是组合

    一个对象的属性是来自另一类的对象,称之为组合。

    为何用组合?

    组合也是用来解决类与类代码冗余的问题

    如何用组合?

    组合的基本形式

    #组合的基本形式
    class Too:#作为另一个对象的属性
        pass
    
    class Bar:
        def __init__(self,too):
            self.too = too
    
    t1 = Too()
    b1 =Bar(t1)

    为什么解决冗余代码

    class Too:
        a =1111
        def __init__(self,x,y):
            self.x =x
            self.y =y
    
    class Bar:
        b=222
        def __init__(self,m,n,too):
            self.m=m
            self.n=n
            self.too =too
    
    t1 = Too(1,2)
    b1 = Bar(5,10,t1)
    b2 = Bar(10,20,t1)
    #Bar类中实际上需要too的三个属性,但是init定义的话,
    # 创建需要每次定义多三个参数
    #使用组合这种方式不仅可以使用t1对象中数据和函数属性,还可使用类的属性
    print(b1.too.x)
    #1
    print(b1.too.a)
    #1111
    #传值减少繁琐,同时Too类,面对复杂的类也可以条理明细

    举例:

    #继承也可以减少冗余代码
    class SchoolMan:
        def __init__(self,name,age,gender):
            self.name =name
            self.age = age
            self.gender = gender
    
    class Course:
        def __init__(self,name,period,price):
            self.name= name
            self.period =period
            self.price = price
    
    #需要课程信息,
    class Student(SchoolMan):
        def __init__(self,name,age,gender,course):
            super().__init__(name,age,gender)
            self.course = course
        def check_course(self):
            print('<name %s>选择<course %s period %s price %s>'
                  %(self.name,self.course.name,self.course.period,self.course.price))
    
    #老师类同样需要课程信息
    class Teacher(SchoolMan):
        def __init__(self,name,age,gender,course,level,salaries):
            super().__init__(name,age,gender)
            self.course = course
            self.level = level
            self.salaries =salaries
    
        def check_course_info(self):
            print('<course %s period %s price %s>'
                  % ( self.course.name, self.course.period, self.course.price))
    
    c1 = Course('python','5month',30000)
    s1= Student('s1',18,'male',c1)
    t1 =Teacher('egon',18,'male',c1,10,5000)
    s1.check_course()
    t1.check_course_info()
  • 相关阅读:
    Shuffle Cards
    求和VII
    Finite Encyclopedia of Integer Sequences(找规律)
    Codeforces Round #223 (Div. 2) C
    Codeforces Round #223 (Div. 2) A
    题目1047:素数判定
    Codeforces Round #219 (Div. 1) C. Watching Fireworks is Fun
    Codeforces Round #219 (Div. 2) B. Making Sequences is Fun
    中南大学第一届长沙地区程序设计邀请赛 New Sorting Algorithm
    中南大学第一届长沙地区程序设计邀请赛 To Add Which?
  • 原文地址:https://www.cnblogs.com/msj513/p/9843652.html
Copyright © 2011-2022 走看看