代码之家  ›  专栏  ›  技术社区  ›  Charles Anderson

在Python中,如何获取成员函数类的名称?

  •  11
  • Charles Anderson  · 技术社区  · 16 年前

    我有一个函数接受另一个函数作为参数。如果函数是类的成员,我需要找到该类的名称。例如。

    def analyser(testFunc):
        print testFunc.__name__, 'belongs to the class, ...
    

    我想

    testFunc.__class__ 
    

    可以解决我的问题,但这只是告诉我testfunc是一个函数。

    4 回复  |  直到 8 年前
        1
  •  13
  •   twasbrillig    10 年前
    testFunc.im_class
    

    https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy

    im_class 是类 im_self 对于 绑定方法或请求的类 对于未绑定方法

        2
  •  11
  •   Conchylicultor    8 年前

    从python 3.3, .im_class 消失了。你可以使用 .__qualname__ 相反。以下是相应的政治公众人物: https://www.python.org/dev/peps/pep-3155/

    class C:
        def f(): pass
        class D:
            def g(): pass
    
    print(C.__qualname__) # 'C'
    print(C.f.__qualname__) # 'C.f'
    print(C.D.__qualname__) #'C.D'
    print(C.D.g.__qualname__) #'C.D.g'
    
        3
  •  5
  •   C. K. Young    16 年前

    我不是巨蟒专家,但这行吗?

    testFunc.__self__.__class__
    

    它似乎适用于绑定方法,但在您的情况下,您可能正在使用未绑定方法,在这种情况下,这可能会更好地工作:

    testFunc.__objclass__
    

    这是我使用的测试:

    Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) 
    [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import hashlib
    >>> hd = hashlib.md5().hexdigest
    >>> hd
    <built-in method hexdigest of _hashlib.HASH object at 0x7f9492d96960>
    >>> hd.__self__.__class__
    <type '_hashlib.HASH'>
    >>> hd2 = hd.__self__.__class__.hexdigest
    >>> hd2
    <method 'hexdigest' of '_hashlib.HASH' objects>
    >>> hd2.__objclass__
    <type '_hashlib.HASH'>
    

    哦,是的,还有一件事:

    >>> hd.im_class
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'builtin_function_or_method' object has no attribute 'im_class'
    >>> hd2.im_class
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'method_descriptor' object has no attribute 'im_class'
    

    所以如果你想要防弹的,它应该 __objclass__ __self__ 也是。但是你的里程数可能会有所不同。

        4
  •  3
  •   JimB    16 年前

    实例方法将具有属性.im_class.im_func.im_self

    http://docs.python.org/library/inspect.html#types-and-members

    您可能想看看函数是否有hasattr.im ou类,并从中获取类信息。