1

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

E.g.

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

That is

create_object(QtGui.QLineEdit, 'myname')

equals to

myname = QtGui.QLineEdit(self)

3 Answers 3

1

To create local variable, you can get the dictionary of global variables using globals() function . Example -

gbl = globals()
gbl['myname'] = QtGui.QLineEdit
gbl['test'] = 1234
test
>> 1234

For local variables with locals() function , which returns the dictionary of local variables (a copy of the local namespace) , you may use this to set the variable, only if you are outside a function and directly in the script part, but setting to the dictionary provided by locals() would not work inside a function (you will not be able to access that variable , even in that function) , when using it outisde the function it has exactly same effect as globals().

Sign up to request clarification or add additional context in comments.

13 Comments

You cannot use locals to define local variables.
Yes, you can, did you try it?
You probably didn't try it.
What do you mean, my above pasted code works (If you take out the Qt stuff, which is something specific to OP's question). Please, note local() means local to the script, not local to function
only because locals() is globals().
|
1

You can use globals. Example:

class A:
    a = 'Hello'

test = globals()['A']
print test.a #It will print 'Hello'

For more information: http://www.diveintopython.net/html_processing/locals_and_globals.html

Comments

0

You can create an attribute with a string specifying the object name with setattr(), like this:

setattr(sys.modules[__name__], 'myname', QtGui.QLineEdit)

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.