Reputation: 923
So I came across this answer for calling class method from another class. Now my question why have they done things using so much complexity when this can be achieved simply by this code:
class a(object):
def __init__(self):
pass
def foo(self):
print('Testing')
class b(object):
def __init__(self, c):
c.foo()
A = a()
B = b(A)
And the output is:
Testing
So what is wrong in my approach? Am I missing something?
Upvotes: 0
Views: 142
Reputation: 22061
Basically, because of the Zen of Python which says:
Explicit is better than implicit.
Complex is better than complicated.
From the OOD (object-oriented design) perspective you are having strong dependencies between two classes, since you cannot initialize B without calling specific method of class A, that may be ok for now, but moving forward such dependency may lead to the problems in long time run. To get deeper understanding of that make sure you are familiart Single responsibility principle and Separation of concerns principles.
Generally speaking - If some method of the another class shall be always called during initializing, maybe that method shall be moved out from another class. As an alternative, you can create utility function which will handle that without introducing hard dependency between classes.
Also, the solution provided in the SO question differs, since it has dynamic call of the method to the name isn't hardcoded like in your sample.
Upvotes: 3