2017-02-28 18 views
2

考慮下面的程序:Python:你能從包含函數的變量中找到父類嗎?

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)) 

...沒什麼明顯的返回。

回答

2

看那__wrapped__ dunder:

>>> y.__wrapped__ 
__main__.MyClass 

functools.update_wrapper添加此屬性。

我也想指出,您使用update_wrapper有點奇怪。在這裏使用my_functionanother_function而不是another_functioncls更爲常見。然後,您將通過__wrapped____self__訪問類對象。

+0

我想我的例子很糟糕。我有一個變量,其中包含在這裏調用as_view()的結果https://github.com/django/django/blob/master/django/views/generic/base.py#L47,但它沒有__wrapped__屬性。感謝指針,它可以與我的示例應用程序一起工作。 –

0

當您打印the_func時,您會看到函數對象。 所以the_func.__name__會給你這個函數被包裝的類名的名字!

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.__name__)                          
    #MyClass 

x = MyClass()                            
y = x.my_function()                          

do_something(y)  
相關問題