Composition

python

#1

I started to read deeper into classes after the python intro and I have a question about compositions.

If I want to take advantage of another class but not in an inheritance way, I use composition and I fully grasp that.

But then it struck me, in order to take advantage of the composition both classes must take the same arguments?


#2

That is really a concern of seamless implementation. It is not a mandatory approach, though since each of the classes composed into this have their own __init__ method which may have additional parameters. The trick would be to have default parameters in the included class if the composite class does not have the parameters.

class Someclass:
    def __init(a, b, c=1):
        self.a = a
        self.b = b
        self.c = c

When instantiating said class, the third argument is optional.


#3

Ok thanks for that explanation. So essentially, the first arguments in the init function must align with the arguments of the other class?


#4

That makes sense but it would be a good idea to read up on it to get the full scoop.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.