Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.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 - Fatal编程技术网

Python 从字典动态构建类属性

Python 从字典动态构建类属性,python,Python,我想动态地构建类属性 # Code label = Label(); label.port = 'JTAG'; ##works # Attribute name in a variable field_name = 'port'; label.field_name = 'port'; ## do not work. # Foreign key mapping. label.foreign_key.port_name = 'port'; ## should w

我想动态地构建类属性

# Code  
label = Label();  
label.port = 'JTAG';  ##works  

# Attribute name in a variable  
field_name = 'port';  
label.field_name = 'port'; ## do not work.  

# Foreign key mapping.    
label.foreign_key.port_name = 'port'; ## should work for foreign_key  
我不想在这里使用setattr,因为我将外键对象映射到此对象。其中,外键的setattr失败


最后,我想在动态构建类对象属性时插入'field_name'变量。请在不使用setattr的情况下告诉我该方法。

以下方法可以解决此问题:

label.__dict__[field_name] = 'port' 

自定义类实例的所有属性在内部存储为字典obj。标签是您自己定义的类还是某个模块的给定类?作为一个起点,您可以结合class.\uuuu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。在这里,我认为在将dict键作为类属性添加之前,必须先对其进行插值。我不想在这里使用setattr的原因是,如果setattr也是外键,我可以进行更新。