Python __init__ and classmethod, do they have to have the same number of args?

dejdej picture dejdej · Mar 19, 2018 · Viewed 12.3k times · Source

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?

Answer

Ajax1234 picture Ajax1234 · Mar 19, 2018

__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