Skip to main content
 首页 » 编程设计

python匿名类变量名

2025年05月04日9softidea

我是 python 匿名类的新手。我在网上找到这段代码

class Struct(object): 
    def __init__(self, **kwargs): 
        self.__dict__.update(kwargs) 
 
    def __repr__(self): 
        d = self.__dict__ 
        results = [type(self).__name__ + "("]  # or: self.__class__.__name__ 
        for key in sorted(d.keys()): 
            if (len(results) > 1): results.append(", ") 
            results.append(key + "=" + repr(d[key])) 
        results.append(")") 
        return "".join(results) 
 
    def __eq__(self, other): 
        return self.__dict__ == other.__dict__ 
 
    def __hash__(self): 
        return hash(repr(self)) # inefficient but simple 

用法是

obj = Struct(x=1, y=2, c=3) 
obj.x #1 
obj.y #2 

我想知道如何动态分配变量名。

我正在尝试做这样的事情

for i, item in enumerate(row): 
    object = Struct() 
    a = (header[i]) 
    object.a= item 

显然这是错误的,object.a中的a是字符串a。我怎样才能动态地做到这一点?

请您参考如下方法:

使用setattr函数,创建一个属性。引用文档,

The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

因此,在您的情况下,您可以使用 header[i] 中的值创建一个属性,如下所示

setattr(obj, header[i], item)