在python3中将类实例化为未知变量名

时间:2013-01-28 01:33:09

标签: python class dynamic python-3.x

我正试图在未知doms中实例化来自未知nodeName的类(不使用eval())。

我希望在node中假设dom nodedom tree时,执行类似伪代码的操作:

# create dom and get a node

class SuperNode(node):
    def __init__(self):
        # do narly node stuff

但我想根据节点名创建类,这样就不知道了。

makeInstance(SuperNode, node.nodeName, node)

为了澄清,node.nodeName是我想要成为实例的变量名的节点的名称。所以,如果node.nodeName = 'clarence'就像这样实例化它(我会担心以后按字母顺序对节点名进行字母顺序以符合类命名):

clarence = SuperNode(node) ''' where node is the node specified 
                               by the name clarence'''

如果名称已知,构造函数将是这样的:

makeInstance(SuperNode, 'clarence', node) ''' where clarance will be the 
                                              instantiated variable of 
                                              class SuperNode'''

这类似于使用setattrib:

设置属性
setattr(class instance, attribute, value)

可以在变量中定义属性。

如果有一个问题如何访问这些名称,它们将在另一个类中定义,然后可以检查整个dom。

有办法做到这一点吗?

一个例子是狗的XML文件,包括狗名,品种,生日等元素。每只狗都是我最初的dom类下的一个超类节点,在每个SuperNode实例中都“神奇地”设置了所有属性< / p>

1 个答案:

答案 0 :(得分:1)

终于找到了我需要做的事情,遗憾的是,答案已经在上面了(有点谦虚总是好的)。在包装对象时,只需使用setattr,如:

>>> class SuperClass():
...     def print_hello(self):
...         print('Hello, world!')

>>> class WrapperClass():
...     pass

>>> wrapper = WrapperClass()
>>> setattr(wrapper, 'clarence', SuperClass())

>>> wrapper.clarence.print_hello()
Hello, world!
>>> 

实际上,我将在包装类型类中使用代码,因此它将是:

setattr(self, 'clarence', SuperClass())

如果要在全局范围内执行此操作,请使用globals()分配如下值:

>>> globals()['clarence'] = SuperClass()
>>> clarence.print_hello()
Hello, world!