2008-11-20 55 views
8

我有一个函数将另一个函数作为参数。如果该函数是一个类的成员,我需要找到该类的名称。例如。在Python中,如何获取成员函数类的名称?

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

我想

testFunc.__class__ 

将解决我的问题,但只是告诉我,testFunc是一个函数。

回答

5

我不是Python专家,但是这样做的工作?

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__。但你的里程可能会有所不同

+0

不,给你的留言:“AttributeError的:‘功能’对象有没有属性‘__self__’”。 – 2008-11-20 16:39:31

+0

尝试__objclass__属性并查看是否有效。如果是这样,那么你的功能是解除绑定的。 – 2008-11-20 16:43:48

4

从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' 
相关问题