我正在尝试用 Python 创建一个对象列表。下面的代码应该(希望)解释我在做什么:
class Base(object):
@classmethod
def CallMe(self):
out = []
#another (models) object is initialised here which is iterable
for model in models:
#create new instance of the called class and fill class property
newobj = self.__class__()
newobj.model = model
out.append(newobj)
return out
class Derived(Base):
pass
我正在尝试按如下方式初始化类:
objs = Derived.CallMe()
我希望“objs”包含一个我可以迭代的对象列表。
我在堆栈跟踪中收到以下错误:TypeError: type() takes 1 or 3 arguments on the line that contains newobj = self.__class__()
有什么方法可以做到这一点,还是我看问题的方式不对?
请您参考如下方法:
问题是 classmethod 没有接收实例 (self) 作为参数。相反,它接收到对其调用的类对象的引用。通常这个参数被命名为 cls,虽然这个约定比 self 的约定稍微弱一些(你偶尔会看到带有名称的代码,比如 klass).
因此,与其调用 self.__class__() 来创建您的实例,不如调用 cls()。如果函数作为 Derived.CallMe() 调用,您将获得 Derived 实例,如果作为 Base 调用,您将获得 .Base 实例。 CallMe()
@classmethod
def CallMe(cls): # signature changed
out = []
models = something()
for model in models:
newobj = cls() # create instances of cls
newobj.model = model
out.append(newobj)
return out
