There is no one single good canonical covering make
/from_<type>
classmethods/ multiple constructors in Python, and also Python has some language-design differences to Java/C/C++.
How should we create a good canonical?
Here are some which each address parts of this.
- What is a clean, pythonic way to have multiple constructors in Python?
- Where possible, it's Pythonic to overload
__init__()
with multiple arguments with default values=None and handling 'magic' cases inside the__init__()
method
- Where possible, it's Pythonic to overload
- How to overload __init__ method based on argument type? / Multiple constructors: the Pythonic way? [duplicate]
- Function overloading '__init__()` with multiple pass-by-name signatures (the Java way) having different argument types and number is not allowed
- However you can use default parameters or **kwargs and *args arguments.
- Make staticmethods or classmethods with the @staticmethod or @classmethod decorator to return an instance of your class, or to add other constructors (
from_file
/from_tuple
/...). But sometimes you can avoid this by introspecting on the argument types (is it a file? string-buffer? tuple?)
- Function overloading '__init__()` with multiple pass-by-name signatures (the Java way) having different argument types and number is not allowed
- Multiple constructors in python? [duplicate]
- What is the difference between @staticmethod and @classmethod in Python?
- Factory method for python object - best practice
- Since there is less need for multiple constructors the Java way (
from_type1(), from_type2(),...
), there is less need in Python for factory methods, and often you can avoid them by using the above practices for a smarter__init__()
- Since there is less need for multiple constructors the Java way (
- (still looking for good explanations of when and where
__new__
is needed; for overriding defaults of builtin types, from classmethods)