【发布时间】:2018-08-28 11:22:10
【问题描述】:
所以类方法可以用作python中的替代“构造函数”,它们绑定到类而不是实例,到目前为止非常清楚。但我的问题是,如果在返回的类方法实例中必须具有与__init__ 中相同数量的参数。更确切地说:
class MyClass(object):
def __init__(self,name):
self.name=name
@classmethod
def alternative_init(cls,name,surname):
return cls(name,surname)
如果我尝试创建一个实例 Myclass("alex") 工作正常,但是如果我尝试创建一个实例 Myclass.alternative_init("alex","james") 我有一个 TypeError ,因为我传递了许多参数,并且 init 只需要 2 。我错过了什么吗?
【问题讨论】:
-
cls(name,surname)通话__init__. -
谢谢,现在明白了。
-
不,它们不必有相同数量的参数,你可以让
alternative_init()做它的代码所说的任何事情。但是Myclass.alternative_init("alex","james")应该给出什么?一个包含名称列表的实例?两个实例? (从生成器产生?作为列表?)还是什么?
标签: python oop constructor arguments class-method