0

有没有更好的方法来获取类中的函数名。

我想得到和<str> "A.boo"不使用self.boo语句。

这是test.py我跑的

import sys
import traceback

def foo():
    print(foo.__name__)
    print(foo.__qualname__)
    print(sys._getframe().f_code.co_name)
    print(traceback.extract_stack()[-2])


foo()

class A:
    def boo(self):
        print(self.boo.__name__)
        print(self.boo.__qualname__)
        print(sys._getframe().f_code.co_name)
        print(traceback.extract_stack()[-2])

A().boo()

输出:

$ python test.py
foo
foo
foo
<FrameSummary file test.py, line 12 in <module>>
boo
A.boo
boo
<FrameSummary file test.py, line 21 in <module>>
4

1 回答 1

1
import inspect


class A:
    def boo(self):
        print(self.__class__.__name__, end=“.”)
        print(inspect.currentframe().f_code.co_name)

Another way:

from decorator import decorator

@decorator
def prints_merhod_name(method, *args, **kwargs):
    self = args[0]
    print(self.__class__.__name__, method.__name__, sep=“.”)
    return method(*args, **kwargs)


class A:
    @prints_method_name
    def foo(self):
    whatever
于 2018-04-27T09:14:41.057 回答