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

Cha*_*son 12 python reflection metaprogramming

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

def analyser(testFunc):
    print testFunc.__name__, 'belongs to the class, ...
Run Code Online (Sandbox Code Playgroud)

我想

testFunc.__class__ 
Run Code Online (Sandbox Code Playgroud)

会解决我的问题,但这只是告诉我testFunc是一个函数.

Con*_*tor 16

从python 3.3,.im_class已经不见了.你可以.__qualname__改用.以下是相应的PEP: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'
Run Code Online (Sandbox Code Playgroud)


Pio*_*cki 14

testFunc.im_class
Run Code Online (Sandbox Code Playgroud)

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

im_classim_self绑定方法的类或要求未绑定方法的方法的类


Chr*_*ung 5

我不是Python专家,但这有用吗?

testFunc.__self__.__class__
Run Code Online (Sandbox Code Playgroud)

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

testFunc.__objclass__
Run Code Online (Sandbox Code Playgroud)

这是我用过的测试:

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'>
Run Code Online (Sandbox Code Playgroud)

哦,是的,另一件事:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

所以,如果你想要的东西刀枪不入,就应该处理__objclass____self__也.但你的里程可能会有所不同