Katsu Katsu - 2 years ago 197
Python Question

composition and aggregation in python

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

If I understood:

  1. Aggregation:

class B:

class A(object):
def __init__(self):
self.B = B

  1. Composition:

In other languages I saw this implemented as a pointer to B. I guess here
is a pointer in python.

class A(object):
def __init__(self, B):
self.B = B

Is it right?

Answer Source

If I understand correctly, aggregation vs composition is about the responsibilities of an object to its members (e.g. if you delete an instance, do you also delete its members?).

Mainly, it will depend a lot on the implementation. For example, to create a class A which receives an instance of class B (aggregation), you could write the following:

class B(object): pass

class A(object):
    def __init__(self, b):
        self.b = b

b = B()
a = A(b)

But as a point of caution, there is nothing built-in to Python that will prevent you from passing in something else, for example:

a = A("string") # still valid

If you would like to create the instance of B inside the constructor of A (composition), you would write the following:

class A(object):
    def __init__(self):
        self.b = B()

As an aside, in your first example, you are setting B to the class definition of B, not to an instance of it:

class A(object):
    def __init__(self):
        self.B = B

>>> a = A()
>>> a.B # class definition
<class __main__.B at 0x028586C0>
>>> a.B() # which you can make instances of
<__main__.B instance at 0x02860990>

So, you end up with an instance of A pointing to the class definition of B, which I'm fairly sure is not what you're after. Although, that is generally much harder to do in other languages, so I understand if that was one of the points of confusion.

As a follow up question, are there any particular behaviours attached to aggregation or composition that you're having difficulty implementing? If so, those might be better addressed in a separate, more focused, question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download