Your ChildClass
reference in the Wrapper.method()
is a free variable, meaning it'll be resolved when Wrapper.method()
is called, not when the method is defined.
By the time you call that method, the name ChildClass
will refer to the last class you created.
You either need to provide a scope that has only one unambiguous value for ChildClass
, or otherwise bind the reference at definition time. The latter can be done by using a function parameter default:
class Wrapper():
@classmethod
def method(cls, child_class=ChildClass):
cls.wrapped = child_class()
You can also use a function scope to bind the reference to a local variable in that scope:
def createClasses(parent):
class ChildClass(parent):
pass
class Wrapper():
@classmethod
def method(cls):
cls.wrapped = ChildClass()
return ChildClass, Wrapper
for c in parents:
child, wrapper = createClasses(c)
children.append(child)
wrappers.append(wrapper)
Here, when Wrapper.method
refers to ChildClass
, it'll be looked up in the local namespace of the createClasses
function, and there is only ever going to be one value bound to that name.