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

后端 未结 5 480
小鲜肉
小鲜肉 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:50

    From python 3.3, .im_class is gone. You can use .__qualname__ instead. Here is the corresponding 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'
    

    With nested functions:

    def f():
        def g():
            pass
        return g
    
    f.__qualname__  # 'f'
    f().__qualname__  # 'f..g'
    

提交回复
热议问题