循环并创建对象数组

Mic*_*tes 1 python oop google-app-engine python-2.7

我正在尝试在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
Run Code Online (Sandbox Code Playgroud)

我正在尝试按如下方式初始化该类:

objs = Derived.CallMe()
Run Code Online (Sandbox Code Playgroud)

我希望'objs'包含我可以迭代的对象列表.

我在stacktrace中得到以下错误:TypeError: type() takes 1 or 3 arguments在包含的行上newobj = self.__class__()

有没有办法做到这一点,还是我以错误的方式看待问题?

Blc*_*ght 7

问题是a classmethod不接收instance(self)作为参数.相反,它接收对它被调用的类对象的引用.通常这个参数被命名,cls虽然这个约定的强度不如那个self(并且你偶尔会看到带有名字的代码klass).

所以,不要打电话self.__class__()来创建你的实例,只需要打电话cls().你会得到Derived情况下,如果函数被调用为Derived.CallMe(),或者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
Run Code Online (Sandbox Code Playgroud)