我有两个类,名为pick_up_phone
。
class Work(object):
def pick_up_phone(self):
make_call()
class Home(object):
def pick_up_phone(self):
make_call()
函数make_call
不是该类的一部分。如何在不向函数传递任何内容的情况下打印在函数内部发起函数的类的名称?
例如......
def make_call()
print(????__.class__.__name__)???? <--- prints Home or Work class
答案 0 :(得分:2)
您可以使用inspect模块:
from inspect import getouterframes, currentframe
def make_call():
print getouterframes(currentframe())[-1][-2][0]
class Work(object):
def pick_up_phone(self):
make_call()
class Home(object):
def pick_up_phone(self):
make_call()
Home().pick_up_phone()
Work().pick_up_phone()
输出:
Home().pick_up_phone()
Work().pick_up_phone()
答案 1 :(得分:0)