In Python, how can you get the name of a member function's class?

后端 未结 5 483
小鲜肉
小鲜肉 2020-12-28 08:01

I have a function that takes another function as a parameter. If the function is a member of a class, I need to find the name of that class. E.g.

def analyse         


        
5条回答
  •  半阙折子戏
    2020-12-28 08:43

    I'm not a Python expert, but does this work?

    testFunc.__self__.__class__
    

    It seems to work for bound methods, but in your case, you may be using an unbound method, in which case this may work better:

    testFunc.__objclass__
    

    Here's the test I used:

    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
    
    >>> hd.__self__.__class__
    
    >>> hd2 = hd.__self__.__class__.hexdigest
    >>> hd2
    
    >>> hd2.__objclass__
    
    

    Oh yes, another thing:

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

    So if you want something bulletproof, it should handle __objclass__ and __self__ too. But your mileage may vary.

提交回复
热议问题