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?
cls(name,surname)
calls__init__
. – Tersanctusalternative_init()
do whatever its code says to do. But what isMyclass.alternative_init("alex","james")
supposed to give? One instance containing a list of names? Two instances ? (yield'ed from a generator? as a list?) or what? – Alvar