I want to know how to implement composition and aggregation in UML terms in python.
If I understood:
class B:
pass
class A(object):
def __init__(self):
self.B = B
In other languages I saw this implemented as a pointer to B. I guess here self.B
is a pointer in python.
class A(object):
def __init__(self, B):
self.B = B
Is it right?
Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist. Composition implies a relationship where the child cannot exist independent of the parent.
Aggregation means one object is the owner of another object. Composition means one object is contained in another object. The direction of a relation is a requirement in both Composition and Aggregation. The direction specifies which object contains the other one. Both have a single direction of association.
Composition is a concept that models a has a relationship. It enables creating complex types by combining objects of other types. This means that a class Composite can contain an object of another class Component . This relationship means that a Composite has a Component .
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With