0

I am getting an error in the following code. I used to write the same and it was working correctly. We can do multiple constructors with different parameters. When we run the program, the constructor that has the same number of parameters that the object has will be called.

Could anyone explain me why does this code keep calling the constructor with the 3 parameters all the time? and as a result it throws an error.

class Person:
    def __init__(self, name):
        print("Constructor with only name")
        self.name = name

    def __init__(self, name, age):
        print("Constructor with name and age. Overwrites above implementation.")
        self.name = name
        self.age = age
        self.gender = "female"

p1 = Person("John")
p2 = Person("John", 2 )
print(p2)

I was expecting different init in the program without errors

shaik moeed
  • 5,300
  • 1
  • 18
  • 54

1 Answers1

0

You can use, typing.overload to fix this as show below,

from typing import overload

class Person:
    @overload
    def __init__(self, name:str):
        pass

    @overload
    def __init__(self, name:str, age:int):
        pass

    def __init__(self, name:str, age:int=0):
        self.name = name
        self.age = age
        self.gender = "female"

p1 = Person("John")
p2 = Person("John", 2)
print(p2)

This is just to show that you can have multiple same name method with different definitions.

shaik moeed
  • 5,300
  • 1
  • 18
  • 54