0

Is it possible to create an attribute where attribute name is specified by a string

E.g.

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

That is

create_attribute(QtGui.QLineEdit, 'myname')

equals to

self.myname = QtGui.QLineEdit(self)

I have already questioned similar question Creating an object using string as a name but just to realise it does not solve my second problem!

Community
  • 1
  • 1
Pygmalion
  • 785
  • 2
  • 8
  • 24
  • possible duplicate of [Creating an object using string as a name](http://stackoverflow.com/questions/30966015/creating-an-object-using-string-as-a-name) – khagler Jun 21 '15 at 17:20
  • `create_attribute` doesn't know `self`. So not possible. – Daniel Jun 21 '15 at 17:20

2 Answers2

2

Use setattr:

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

to get the attribute, you can use getattr:

getattr(self, 'myname').setText('bla')
Daniel
  • 42,087
  • 4
  • 55
  • 81
1

You can use the __setattr__() to set the attribute using string .

Example -

class CA:
    pass

c = CA()
c.__setattr__('name','value')
c.__setattr__('myname',QtGui.QLineEdit)
c.name
>> 'value'
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176