Python:你能从包含函数的变量中找到父类吗?

标签 python introspection

给定以下程序:

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_functionanother_function,而不是 another_functioncls。然后,您可以通过 __wrapped__ 和 __self__ 访问类对象。

关于Python:你能从包含函数的变量中找到父类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42499268/

相关文章:

python - 在Mac OS X上安装Python包时如何指定使用的SDK版本?

python - 环境。运行 Minimal Flask 应用程序时未设置变量

python - 从列表中,动态创建具有名称意识的方法

C++ 使用 boost fusion adapt_struct 迭代到嵌套结构字段

python - 在给定完整模块路径的情况下动态导入可调用对象?

c - 使用 CMake 生成 SWIG 绑定(bind)

python - 如何 pickle 继承的异常?

python - Python 中的 MCTS *树* 并行化 - 可能吗?

Python 3.6 : using Simpson's method

python - 如何猴子补丁python列表__setitem__方法