给定以下程序:
from functools import update_wrapper
class MyClass:
@classmethod
def my_function(cls):
def another_function():
print('hello')
return update_wrapper(another_function, cls)
def do_something(the_func):
print(the_func)
# <function MyClass at 0x7f5cb69fd848>
print(the_func.__class__)
# <type 'function'>
print(the_func())
x = MyClass()
y = x.my_function()
do_something(y)
在我的 do_something 函数中,如何识别“the_func”变量来自“MyClass”类?具体来说,如何获得对 MyClass 的未实例化引用?
print(dir(the_func))
...没有返回任何明显的内容。
最佳答案
看看__wrapped__
的错误:
>>> y.__wrapped__
__main__.MyClass
这是 functools.update_wrapper
添加此属性。
我还想指出,您对 update_wrapper
的使用有点奇怪。此处更常见的是使用 my_function
和 another_function
,而不是 another_function
和 cls
。然后,您可以通过 __wrapped__ 和 __self__ 访问类对象。
关于Python:你能从包含函数的变量中找到父类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42499268/