使用字符串作为名称创建属性

问题描述:

是否可以创建属性,其中属性名称由字符串指定使用字符串作为名称创建属性

E.g.

create_attribute(QtGui.QLineEdit, 'myname') 
self.myname.setText = 'created!' 

也就是说

create_attribute(QtGui.QLineEdit, 'myname') 

等于

self.myname = QtGui.QLineEdit(self) 

我已经问类似的问题Creating an object using string as a name但只是为了实现它并没有解决我的第二个问题!

+0

使用字符串作为[创建对象的可能重复名字(http://stackoverflow.com/questions/30966015/creating-an-object-using-string-a s-a-name) – khagler

+0

'create_attribute'不知道'self'。所以不可能。 – Daniel

使用setattr

setattr(self, 'myname', QtGui.QLineEdit(self)) 

获取属性,你可以使用getattr

getattr(self, 'myname').setText('bla') 

您可以使用__setattr__()使用string来设置属性。

示例 -

class CA: 
    pass 

c = CA() 
c.__setattr__('name','value') 
c.__setattr__('myname',QtGui.QLineEdit) 
c.name 
>> 'value'