Python 使用继承和类方法动态创建类列表
我有一个类列表,我正在尝试动态创建另一个类列表,这样每个类都有一个Python 使用继承和类方法动态创建类列表,python,inheritance,dynamic,python-2.7,class-method,Python,Inheritance,Dynamic,Python 2.7,Class Method,我有一个类列表,我正在尝试动态创建另一个类列表,这样每个类都有一个classmethod,它从原始列表创建一个类的子类实例。 问题是,所有方法最终都返回同一类(最后创建的一个)的实例 以下是我的代码的最小化版本: class C1(): var = 1 class C2(): var = 2 parents = (C1, C2) children = [] wrappers = [] for c in parents: class ChildClass(c):
classmethod
,它从原始列表创建一个类的子类实例。问题是,所有方法最终都返回同一类(最后创建的一个)的实例 以下是我的代码的最小化版本:
class C1():
var = 1
class C2():
var = 2
parents = (C1, C2)
children = []
wrappers = []
for c in parents:
class ChildClass(c):
pass
children.append(ChildClass())
class Wrapper():
@classmethod
def method(cls):
cls.wrapped = ChildClass()
wrappers.append(Wrapper)
print(list(child.var for child in children))
for wrapper in wrappers:
wrapper.method()
print(list(wrapper.wrapped.var for wrapper in wrappers))
输出:
[1, 2]
[2, 2]
您可以看到children
列表包含不同的实例,而classmethod
在这两种情况下都创建C2
的子实例
如何修复代码,使每个classmethod
创建正确类的实例
(我使用的是python 2.7.4)您的
Wrapper.method()
中的ChildClass
引用是一个自由变量,这意味着它将在调用Wrapper.method()
时解析,而不是在定义方法时解析
当您调用该方法时,名称ChildClass
将引用您创建的最后一个类
您需要为ChildClass
提供一个只有一个明确值的范围,或者在定义时绑定引用。后者可以通过使用函数参数默认值来完成:
class Wrapper():
@classmethod
def method(cls, child_class=ChildClass):
cls.wrapped = child_class()
还可以使用函数作用域将引用绑定到该作用域中的局部变量:
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)
这里,当
Wrapper.method
引用ChildClass
时,将在createClasses
函数的本地名称空间中查找它,只有一个值绑定到该名称。这是解决方案的问题吗?@BurhanKhalid-我正在使用unittest
测试一个web应用程序。我有一个基本的tester类,我正在为每个浏览器(Firefox、IE等)创建一个子类。每个子类都需要一个setUpClass
(这是一个classmethod
)为其浏览器创建seleniumWebDriver
的实例。