I’m trying to create a list of objects in Python. The below code should (hopefully) explain what I’m doing:
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
I’m trying to initialise the class as follows:
objs = Derived.CallMe()
I want ‘objs’ to contain a list of objects which I can iterate through.
I get the following error in the stacktrace: TypeError: type() takes 1 or 3 arguments on the line that contains newobj = self.__class__()
Is there some way to do this or am I looking at the problem the wrong way?
The issue is that a
classmethoddoesn’t receive an instance (self) as an argument. Instead, it receives a reference to the class object it was called on. Often this argument is namedclsthough this convention is somewhat less strong than the one forself(and you’ll occasionally see code with names, likeklass).So rather than calling
self.__class__()to create your instances, just callcls(). You’ll getDerivedinstances if the function was called asDerived.CallMe(), orBaseinstances if called asBase.CallMe().