简体   繁体   English

Python __init__ 和 classmethod,它们是否必须具有相同数量的 args?

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

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.所以 classmethods 可以用作 python 中的替代“构造函数”,它们绑定到类而不是实例,到目前为止很清楚。 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__ .但我的问题是,是否必须在类方法的返回实例中具有与__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 .如果我尝试创建一个实例Myclass("alex")工作正常,但是如果我尝试创建一个实例Myclass.alternative_init("alex","james")我有一个TypeError ,因为我传递了许多参数,并且init 只需要 2 。 Am I missing something?我错过了什么吗?

__init__ only takes one parameter, the name. __init__只接受一个参数,名字。 Thus, you can pass either name or surname to cls , but not both.因此,您可以将namesurname传递给cls ,但不能同时传递两者。 However, you can create a class instance in classmethod , and add an additional paramter:但是,您可以在classmethod创建一个类实例,并添加一个额外的参数:

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

You could do what you want like this:你可以像这样做你想做的事:

class MyClass(object):
    def __init__(self,name):
        self.name=name

    @classmethod
    def alternative_init(cls,name,surname):
        new_instance = cls(name)
        new_instance.surname = surname
        return new_instance

a = MyClass.alternative_init('Bob', 'Spongy')
print(a.name, a.surname)
# Bob Spongy

Because Myclass.alternative_init("alex","james") calls the cls(name, surname) which same as MyClass(name,surname) which also same as __init__(self,name,surname) but your __init__ function don't have surname parameter.因为Myclass.alternative_init("alex","james")调用与MyClass(name,surname)相同的 cls(name, surname) 也与__init__(self,name,surname)但你的__init__函数没有surname参数。 You can make surname optional by __init__(self,name,surname=None)您可以通过__init__(self,name,surname=None)使surname可选

class MyClass(object):
  def __init__(self,name,surname=None):
     self.name=name
     self.surname=surname

  @classmethod
  def alternative_init(cls,name,surname):
      return cls(name,surname)

In Python, the first argument Passed to a method is always the object itself.在 Python 中,传递给方法的第一个参数始终是对象本身。 If you call now your method with a name, you will get self as first parameter and the name as second.如果您现在使用名称调用您的方法,您将得到 self 作为第一个参数,名称作为第二个参数。

When you call now the init method from inside of your classmethod, python has no idea what it should do with the surname.当您现在从 classmethod 内部调用init方法时,python 不知道它应该对姓氏做什么。

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python - __init__ 参数 - Python - __init__ args Python中的实例变量是否必须在__init__方法中为类初始化? - Do instance variables in Python have to be initialized in the __init__ method for a Class? 用python中的父类方法重写__init__ - Overriding __init__ with parent classmethod in python 在Python中,如果使用* args,是否必须限制args的数量? - In Python if using *args do I have to limit number of args? 是否可以将 python class 声明为与另一个 class 具有相同的 __init__() 签名(包括默认值)? - Can a python class be declared to have the same __init__() signature as another class (including defaults)? @classmethod和python中的__init__方法一起工作吗? - does the @classmethod work together with the __init__ method in python? 如何处理python __init__中缺少的参数? - How to handle missing args in python __init__? 在python __init__中捕获许多args之一 - Capturing one of many args in a python __init__ 在`__init__()` 之外声明的实例变量在python 中有什么不同吗? - Do instance variables declared outside of `__init__()` have any differences in python? python 如何处理 class 中的属性? 我是否总是必须在 __init__ 方法中初始化它们? - How does python handle attribute in a class ? Do I always have to initialize them in __init__ method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM