代码之家  ›  专栏  ›  技术社区  ›  Sam Dolan

如何在Python中获得类引用的具体名称(例如“<module\u name>”、“<class\u name”>)?

  •  1
  • Sam Dolan  · 技术社区  · 15 年前

    到目前为止,我的情况是:

    def get_concrete_name_of_class(klass):
    """Given a class return the concrete name of the class.
    
    klass - The reference to the class we're interested in.
    """
    
    # TODO: How do I check that klass is actually a class?
    # even better would be determine if it's old style vs new style
    # at the same time and handle things differently below.
    
    # The str of a newstyle class is "<class 'django.forms.CharField'>"
    # so we search for the single quotes, and grab everything inside it,
    # giving us "django.forms.CharField"
    matches = re.search(r"'(.+)'", str(klass))
    if matches:
        return matches.group(1)
    
    # Old style's classes' str is the concrete class name.
    return str(klass)
    

    所以这个方法很好用,但是对类的字符串进行正则表达式搜索似乎很不成熟。注意我不能就这么做 klass().__class__.__name__ (无法处理args等)。

    还有,有人知道如何完成TODO(检查 klass 是一个类,它是旧样式还是新样式?

    根据这些评论,我的结论是:

    def get_concrete_name_of_class(klass):
        """Given a class return the concrete name of the class.
    
        klass - The reference to the class we're interested in.
    
        Raises a `TypeError` if klass is not a class.
        """
    
        if not isinstance(klass, (type, ClassType)):
            raise TypeError('The klass argument must be a class. Got type %s; %s' % (type(klass), klass))
    
        return '%s.%s' % (klass.__module__, klass.__name__)
    
    3 回复  |  直到 15 年前
        1
  •  2
  •   Ned Batchelder    15 年前

    klass.__name__ ,或获取完全限定名, klass.__module__+'.'+klass.__name__ ?

        2
  •  2
  •   Eli Courtwright    15 年前

    你可以说

    klass.__module__ + "." + klass.__name__
    

    至于如何判断某个类是旧类还是新类,我建议说

    from types import ClassType  # old style class type
    
    if not isinstance(klass, (type, ClassType)):
        # not a class
    elif isinstance(klass, type):
        # new-style class
    else:
        # old-style class
    
        3
  •  1
  •   S.Lott    15 年前
    >>> class X:
    ...     pass
    ... 
    >>> class Y( object ):
    ...     pass
    ... 
    

    type函数告诉您名称是类还是旧样式还是新样式。

    >>> type(X)
    <type 'classobj'>
    >>> type(Y)
    <type 'type'>
    

    它还告诉你一个物体是什么。

    >>> x= X()
    >>> type(x)
    <type 'instance'>
    >>> y= Y()
    >>> type(y)
    <class '__main__.Y'>
    

    你可以通过简单的询问它是什么的子类来测试旧样式和新样式。

    >>> issubclass(y.__class__,object)
    True
    >>> issubclass(x.__class__,object)
    False
    >>> 
    
    推荐文章