So classmethods can be used as an alternative "constructor" in python, they are bound to the class and not to an instance, pretty clear so far. But my question is, if it is mandatory to have the same number of arguments in the returned instance of the class method as in the __init__
. More exactly :
class MyClass(object):
def __init__(self,name):
self.name=name
@classmethod
def alternative_init(cls,name,surname):
return cls(name,surname)
And if I try to create an instance Myclass("alex")
works fine, but if I try to create an instance Myclass.alternative_init("alex","james")
I have a TypeError
, because I pass to many arguments, and init take only 2 . Am I missing something?
There are a number of ways that an __init__ method may be be called more than once. There may be more than one explicit call to the method in the hierarchy of __init__ methods. A class using multiple inheritance directly calls the __init__ methods of its base types.
Python does not support explicit multiple constructors, yet there are some ways using which the multiple constructors can be achieved. If multiple __init__ methods are written for the same class, then the latest one overwrites all the previous constructors.
How Does the __init__ Method Work? The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose.
We can declare a __init__ method inside a class in Python using the following syntax: class class_name(): def __init__(self): # Required initialisation for data members # Class methods … … Let's take an example of a class named Teacher in Python and understand the working of __init__() method through it better.
__init__
only takes one parameter, the name. Thus, you can pass either name
or surname
to cls
, but not both. However, you can create a class instance in classmethod
, and add an additional paramter:
class MyClass(object):
def __init__(self,name):
self.name=name
def __setattr__(self, name, val):
self.__dict__[name] = val
@classmethod
def alternative_init(cls,name,surname):
v = cls(name)
v.surname = surname
return v
class MyClass(object):
def __init__(self,name):
self.name=name
@classmethod
def alternative_init(cls,name,surname):
return cls(name)
a = MyClass("alex")
MyClass.alternative_init("alex","james")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With