如何获取python调用者对象信息?

use*_*873 6 python introspection

如何从函数内获取调用者对象,并检查有关该调用者的信息?

\n\n
class A(object):\n    def class_A_fun(self):\n            print \'caller from class\'  # \xe2\x86\x92 B\n            print \'caller from method\'  # \xe2\x86\x92 class_B_fun\n            print \'caller module\'  # \xe2\x86\x92 foomodule\n            print \'caller instance\'  # \xe2\x86\x92 obj\n            print \'caller object file name or path\'  # \xe2\x86\x92 \'foomodule.py\'\n\nclass B(object):\n    def class_B_fun(self):    \n        obj = A()\n        obj.class_A_fun()        \n\nif __name__ == "__main__":\n    obj = B()\n    obj.class_B_fun()\n
Run Code Online (Sandbox Code Playgroud)\n

big*_*ose 1

并非所有这些都是可能的,但大多数都可以通过检查调用堆栈来获得:

import sys
import inspect

__metaclass__ = type

class Lorem:
    def ipsum(self):
        caller_frame = sys._getframe(1)
        caller_frameinfo = inspect.getframeinfo(caller_frame)
        print("Caller is in module {module!r}".format(
                module=inspect.getmodule(caller_frame)))
        print("Caller is defined in {path!r}, line {lineno}".format(
                path=inspect.getsourcefile(caller_frame),
                lineno=caller_frameinfo.lineno))

class Dolor:
    def sit_amet(self):
        lorem = Lorem()
        lorem.ipsum()
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅inspect模块的文档。

  • 那么调用者*class*呢? (2认同)