Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用继承和类方法动态创建类列表_Python_Inheritance_Dynamic_Python 2.7_Class Method - Fatal编程技术网

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
)为其浏览器创建selenium
WebDriver
的实例。