Skip to main content
 首页 » 编程设计

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

2024年10月01日652php

给定以下程序:

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__ dunder:

>>> y.__wrapped__ 
__main__.MyClass 

是functools.update_wrapper添加此属性。

我还想指出您对 update_wrapper 的使用有些奇怪。在这里使用 my_function 和 another_function 而不是 another_function 和 cls 会更常见。然后,您将通过 __wrapped__ 和 __self__ 访问类对象。