本文介绍了在Python中使用for循环添加类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从字典中生成一个类:

I was trying to generate a class from a dictionary:

class attr:
    for key in objects_type:
        setattr(attr, key, lambda cl: list())

这给出了在for循环中未定义attr的错误.我知道我会写:

This gives the error that attr is not defined during the for loop. I know I could write:

class attr:
    pass
for key in objects_type:
    setattr(attr, key, lambda cl: list())

但是我敢肯定,我记得在某处看到类似于第一个示例的代码.有谁知道是否可以写类似于第一种形式的东西?

But I am sure I remember seeing code similar to the first example somewhere. Does anyone know if it is possible to write something similar to the first form?

推荐答案

虽然不是很优雅,但是您可以使用locals():

Although it's not very elegant, you can use locals():

>>> class c(object):
...     for i in range(10):
...         locals()['A' + str(i)] = i
... 
>>> c.A0
0
>>> c.A7
7

这篇关于在Python中使用for循环添加类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:29