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
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
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.