Python Forum
Number of constructors allowed in a Python class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Number of constructors allowed in a Python class
#1
Hello,
I realize this is a very simple question but I have seen some information online that is slightly contradictory on this. How many constructors can a Python class have? Is it that every Python class must have one AND ONLY ONE __init__ constructor? This is not a homework question - just trying to understand this concept from the forum. This doesn't seem to specifically be addressed in the Python docs.

https://docs.python.org/3/reference/data...l#index-69

object.__init__(self[, ...])
Called after the instance has been created (by __new__()), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an __init__() method, the derived class’s __init__() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: super().__init__([args...]).

Thank you in advance for your help with this newbie question,
crocolicious
Reply
#2
Each class has only one __init__ method. If you write another with a different signature, that won't become another constructor, it will just overwrite the previous __init__ method.

Alternate constructors are often done as class methods. So if you have a Foo class, you might call Foo.from_text(some_string), which could return an instance of the Foo class.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
And the point of "one and only one" is incorrect, it is "up to one". An __init__ method is not required.
Reply
#4
To caveat, while you can only have one __init__() function, you can use keyword arguments with default values to simulate the functionality of multiple constructors.

In languages allowing multiple constructors, the alternatives are used for different data types or a different number of arguments. Python is dynamically typed so an alternate constructor is not needed for different data types. Depending on the data types in question, you may need a conditional to check for data type, but it's otherwise not an issue. For different numbers of arguments, Python typically uses keyword arguments with default values (often None); check out the function signature for open() as an example.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020