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

时间:2008-11-20 16:30:31

标签: python reflection metaprogramming

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

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

我想

testFunc.__class__ 

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

5 个答案:

答案 0 :(得分:14)

testFunc.im_class

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

  

im_classim_self的类   约束方法或要求的类   对于未绑定方法的方法

答案 1 :(得分:13)

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

答案 2 :(得分: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__。但你的里程可能会有所不同。

答案 3 :(得分:3)

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

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

您可能想查看函数是否为.at_class,并从那里获取类信息。

答案 4 :(得分:0)

请使用以下函数在类内部获取方法名称

def getLocalMethods(clss):
import types
# This is a helper function for the test function below.
# It returns a sorted list of the names of the methods
# defined in a class. It's okay if you don't fully understand it!
result = [ ]
for var in clss.__dict__:
    val = clss.__dict__[var]
    if (isinstance(val, types.FunctionType)):
        result.append(var)
return sorted(result)