Re: Reflectiong capabilityof Python
- From: Rafe <rafesacks@xxxxxxxxx>
- Date: Tue, 25 Nov 2008 20:54:37 -0800 (PST)
On Nov 26, 9:18 am, goat...@xxxxxxxxx wrote:
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:
obj = type("ClassA", object, {}) # The base class is object
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
.
- References:
- Reflectiong capabilityof Python
- From: goatold
- Reflectiong capabilityof Python
- Prev by Date: Re: How to get a directory file descriptor?
- Next by Date: Re: How to get a directory file descriptor?
- Previous by thread: Re: Reflectiong capabilityof Python
- Index(es):