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

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.