代码之家  ›  专栏  ›  技术社区  ›  zsquare lance

按名称初始化类对象

  •  24
  • zsquare lance  · 技术社区  · 14 年前

    例如,

    class Foo:
        """Class Foo"""
    

    c = get_class("Foo")

    3 回复  |  直到 14 年前
        1
  •  44
  •   Brian McKenna    14 年前

    如果该类在您的范围内:

    get_class = lambda x: globals()[x]
    

    getattr :

    import urllib2
    handlerClass = getattr(urllib2, 'HTTPHandler')
    
        2
  •  1
  •   Michael Mior    12 年前

    你听说过 inspect module

    退房 this snippet 我发现了。

        3
  •  -2
  •   Michael Mior    12 年前

    我想你的反省 http://en.wikipedia.org/wiki/Reflection_%28computer_science%29#Python

    或者德国维基百科上的一个更好的例子:

    >>> # 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!
    

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