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!

2
  • possible duplicate of Creating an object using string as a name Commented Jun 21, 2015 at 17:20
  • create_attribute doesn't know self. So not possible. Commented Jun 21, 2015 at 17:20

2 Answers 2

2

Use setattr:

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

to get the attribute, you can use getattr:

getattr(self, 'myname').setText('bla')
Sign up to request clarification or add additional context in comments.

Comments

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.