composition and aggregation in python

前端 未结 3 1986
南旧
南旧 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:50

    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 could write the following:

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

    Or, you could inject the class into the constructor, and then create an instance, like so:

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

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

    class A(object):
        def __init__(self, B):
            self.B = B
    
    >>> a = A()
    >>> a.B # class definition
    
    >>> 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.

提交回复
热议问题