0

In Python, can I do something like the following that I did in Java?

I want to have two constructors, a default constructor and one that asks me to send a string.

public class Person
{
   String name;

   public static void main(String[] args)
   {
      Person person = new Person("John");
      Person person2 = new Person();
   }

   public Person()
   {
     name = "No name";
   }

   public Person(String name)
   {
     this.name = name;
   }
}
1

3 Answers 3

1

In Python you wouldn't overload the constructor, but give the name argument a default value:

class Person:
    def __init__(self, name="No Name"):
        self.name = name
Sign up to request clarification or add additional context in comments.

Comments

1

In Python you can't have multiple constructors. The only way is to use these elements:

  • a keyword argument
  • an optional argument with a default value
class Person:
    def __init__(self, name="No name"):
        self.name = name

if __name__ == '__main__':
    p1 = Person()
    p2 = Person("John")

Comments

0

Not without additional library help for faking overloaded functions. The Pythonic equivalent is to define one __init__ method and an additional class method that uses __init__. For example,

class Person:
    def __init__(self, name):
        self.name = name

    @classmethod
    def nameless(cls, self):
        return cls("No name")

person = Person("Jhon")
person2 = Person.nameless()

though in this case, this is overkill for providing a default argument, which can be done with

class Person:
    def __init__(self, name="No name"):
        self.name = name

person = Person("Jhon")
person2 = Person()

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.