开发者

Initialise class object by name

Since everything in python is an object, i was wondering if there 开发者_如何学编程was a way i could initialise a class object using the name of the class

for example,

class Foo:
    """Class Foo"""

How could i access this class by "Foo", ie something like c = get_class("Foo")


If the class is in your scope:

get_class = lambda x: globals()[x]

If you need to get a class from a module, you can use getattr:

import urllib2
handlerClass = getattr(urllib2, 'HTTPHandler')


Have you heard of the inspect module?

Check out this snippet I found.


I think your searching reflection see http://en.wikipedia.org/wiki/Reflection_%28computer_science%29#Python

Or a better Example from the german wikipedia:

>>> # the object
>>> class Person(object):
...    def __init__(self, name):
...        self.name = name
...    def say_hello(self):
...        return 'Hallo %s!' % self.name
...
>>> ute = Person('Ute')
>>> # direct
>>> print ute.say_hello()
Hallo Ute!
>>> # Reflexion
>>> m = getattr(ute, 'say_hello')()
>>> # (equals ute.say_hello())
>>> print m
Hallo Ute!

from http://de.wikipedia.org/wiki/Reflexion_%28Programmierung%29#Beispiel_in_Python

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜