I have a class AbstractDataHandle, whith his init method, and a class Classifier. I would like to have two constructors in Classifier, Java like. One inherited from it`s superclass, and one brand new.
It would be something like (but i intend to "keep" the two constructors):
class AbstractDataHandle():
def __init__(self, elements, attributes, labels):
self._load(elements, attributes, labels)
class Classifier(AbstractDataHandle):
def __init__(self, classifier="LinearSVC", proba=False):
self._fit(classifier, proba)
Can i have two constructors in one class? If yes, can i have a constructor inherited from a superclass, and add a new one?
Thank you in advance.
You can use class methods, which work as factory methods. That's imho the best approach for multiple constructors. First argument 'cls' is class itself, not it's instance, so cls('Truck') in class method invokes constructor for class Car.
Then you call factory method this way:
You can't have two constructors in one class.
Constructors have to be named
__init__
. And, unlike Java, Python doesn't allow overloading functions or methods by the type of their arguments. So, if you had two constructors, they would both be the same function.There are a few ways around this.
Use
@classmethod
s as alternate constructors:A simple example from the standard library is
datetime.datetime
, which can be constructed withnow
,fromtimestamp
, or a few other alternate constructors, besides the default.Use default-valued, keyword-only, and/or variable-argument parameters to make a single constructor that can be called different ways:
int
is an example of this: You can create it from a string and a base, or from a single argument that knows how to convert itself to an integer.Create subclasses that each have different constructors:
In any of these cases, you can factor out commonalities into a single "base" initializer. For example:
Of course in no case is it possible to have breakfast without spam.
There are the methods in the accepted answer, but I think this one is fairly flexible. It's convoluted, but very flexible.
When the class is instiated, init calls a method and pass it a string argument (obtained from instantiation). That function uses conditionals to call the right "constructor" function to initialize your values, let's say you have different sets of possible starting values.
If you need to provide other arguments (e.g. that might have a value only at runtime), you can use default values in init() to allow optional arguments, and initialize those in init as you normally would.
The output of which is: