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;
   }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
FJGJFOR
  • 17
  • 6
  • 3
    Does this answer your question? [What is a clean, pythonic way to have multiple constructors in Python?](https://stackoverflow.com/questions/682504/what-is-a-clean-pythonic-way-to-have-multiple-constructors-in-python) – Tugay Nov 30 '20 at 22:27

3 Answers3

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
Mureinik
  • 297,002
  • 52
  • 306
  • 350
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")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
azro
  • 53,056
  • 7
  • 34
  • 70
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()
chepner
  • 497,756
  • 71
  • 530
  • 681