Reflectiong capabilityof Python

G

goatold

Can Python create object by name? Like
clsName = "ClassA"
aObj = createObjectByName(clsName)
 
M

MRAB

R

Rafe

Can Python create object by name? Like
clsName = "ClassA"
aObj = createObjectByName(clsName)

if you are talking about creating an objcet dynamically and naming the
CLASS name at runtime, use:
If you know the name of the class and you want to get an instance
(object) of it dynamically, there are two ways I have found.

1) use getattr(module, "Class A").

2) Use the globals() dict which is handy when you know the class is
always in the same module as the code that calls it (watch out for
inheritance across more than one module though. This can put the
globals() call in a different module.)

- Rafe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top