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

20 投票
5 回答
42188 浏览
提问于 2025-04-11 19:08

我有一个函数,它可以接收另一个函数作为参数。如果这个函数是某个类的成员,我需要找到这个类的名字。比如说:

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

我原以为

testFunc.__class__ 

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

5 个回答

8

我不是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__。不过具体情况可能会有所不同。

35

从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'

关于嵌套函数的内容:

def f():
    def g():
        pass
    return g

f.__qualname__  # 'f'
f().__qualname__  # 'f.<locals>.g'
14
testFunc.im_class

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

im_classim_self 的类,对于绑定方法来说,im_class 是指那个方法所属的类;而对于未绑定的方法,im_class 则是请求这个方法的类。

撰写回答