composition and aggregation in python

前端 未结 3 1945
南旧
南旧 2020-12-23 17:52

I want to know how to implement composition and aggregation in UML terms in python.

If I understood:

  1. Aggregation:

3条回答
  •  隐瞒了意图╮
    2020-12-23 18:36

    Composition and aggregation are specialised form of Association. Whereas Association is a relationship between two classes without any rules.

    Composition

    In composition, one of the classes is composed of one or more instance of other classes. In other words, one class is container and other class is content and if you delete the container object then all of its contents objects are also deleted.

    Now let's see an example of composition in Python 3.5. Class Employee is container and class Salary is content.

    class Salary:
        def __init__(self,pay):
            self.pay=pay
    
        def get_total(self):
           return (self.pay*12)
    
    class Employee:
        def __init__(self,pay,bonus):
            self.pay=pay
            self.bonus=bonus
            self.obj_salary=Salary(self.pay)
    
        def annual_salary(self):
            return "Total: "  +  str(self.obj_salary.get_total()+self.bonus)
    
    
    obj_emp=Employee(100,10)
    print (obj_emp.annual_salary())
    

    Aggregation

    Aggregation is a weak form of composition. If you delete the container object contents objects can live without container object.

    Now let's see an example of aggregation in Python 3.5. Again Class Employee is container and class Salary is content.

    class Salary:
        def __init__(self,pay):
            self.pay=pay
    
        def get_total(self):
           return (self.pay*12)
    
    class Employee:
        def __init__(self,pay,bonus):
            self.pay=pay
            self.bonus=bonus
    
        def annual_salary(self):
            return "Total: "  +  str(self.pay.get_total()+self.bonus)
    
    
    obj_sal=Salary(100)
    obj_emp=Employee(obj_sal,10)
    print (obj_emp.annual_salary())
    

提交回复
热议问题