0

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?

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
DuttaA
  • 903
  • 4
  • 10
  • 24
  • 1
    The accepted answer is doing dynamic calling, meaning the function name is not fixed in code. That is different from yours where it is fixed. – Sami Kuhmonen Aug 20 '18 at 11:16
  • 2
    Also that is an instance method, not a class method. Also, normally classes are capitalised and instances are lowercase in python. – FHTMitchell Aug 20 '18 at 11:17
  • @SamiKuhmonen what is the difference between dynamic calling and static calling? I mean aren't function names always fixed? – DuttaA Aug 20 '18 at 11:19
  • 1
    The difference is they can call *any* method with the name of the function. They can even ask the user what function should be called. Yours can’t do that unless you add a huge switch/case – Sami Kuhmonen Aug 20 '18 at 11:21
  • @SamiKuhmonen thanks for the clarification – DuttaA Aug 20 '18 at 11:22
  • BTW, `def __init__(self): pass` is only needed if you want a new class instance to not do initialization when its created but it's inherited an `__init__` method from its parent class. If you don't need an `__init__`, just don't define one. – PM 2Ring Aug 20 '18 at 11:54
  • @PM2Ring no no...I was just testing so I wrote pass..But thanks for the information – DuttaA Aug 20 '18 at 11:57

1 Answers1

3

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.

Community
  • 1
  • 1
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82