-1

I want to know that what will happen if we have multiple __init__ methods in the same class? Is the latest __init__ method going to override the earlier __init__ methods? If yes, kindly explain in easy words, what is overriding?

class D:
 
    def __init__(self, x):
        print(f'Constructor 1 with argument {x}')
 
    # is this will overide the above __init__ method?
    def __init__(self, x, y):
        print(f'Constructor 1 with arguments {x}, {y}')

    # is this will overide the above __init__ method?
    def __init__(self):
        pass

James Z
  • 12,209
  • 10
  • 24
  • 44
  • Does this answer your question? [What is a clean "pythonic" way to implement multiple constructors?](https://stackoverflow.com/questions/682504/what-is-a-clean-pythonic-way-to-implement-multiple-constructors) – Ryan Zhang Aug 23 '22 at 11:12
  • The last init will override all constructors before. – Oivalf Aug 23 '22 at 11:13
  • Have you tried running your code example to see what happens. eg. `D()` versus `D(1)`. You'll find out quite quickly what happens. – Dunes Aug 23 '22 at 11:15
  • This is *exactly* the same as doing `x = 1` followed by `x = 2` followed by `x = 3`; only the last assignment remains in effect. – jasonharper Aug 23 '22 at 15:45

3 Answers3

1

So far, from what I have seen, the latest __init__ method seems to have overwritten the earlier ones. Now, I am not sure about the reason, but one possible explanation could be the fact that python is an interpreted language which means it travers code one line at a time

  • The reason is that the earlier functions are removed from the class scope each time the function is redeclared. It works much like how you might expect `a = 1; a = 2` in other languages -- the first value is no longer reachable, and so cannot be used. Python is like C in this respect -- it does not have function overloading. You can an approximation of function overloading using [singledispatch](https://docs.python.org/3/library/functools.html#functools.singledispatch). – Dunes Aug 23 '22 at 11:22
0

Yes, it would kind of "override" it. I looked it up once few weeks ago on google and the answer was that it would not work. The better way would be to have:

 def __init__(self, *args):
    if len(args) == 1:
      print(f'Constructor 1 with argument {x}')

    if len(args) == 2:  
      print(f'Constructor 1 with arguments {x}, {y}')

    if len(args) == 0:  
        pass

I think you can find it by www.geeksforgeeks.org

Leo
  • 9
  • 3
-1

In other languages this is called overflow, where we can create multiple constructors based on different input (extremely useful) but python doesn't support it. One thing is that I'm guessing its possible because of how python handles inheritance, the second init over riding the first in the same way a inherited classes init overrides the base classes.

Bryn
  • 27
  • 2