考慮下面的程序: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))
...沒什麼明顯的返回。
我想我的例子很糟糕。我有一個變量,其中包含在這裏調用as_view()的結果https://github.com/django/django/blob/master/django/views/generic/base.py#L47,但它沒有__wrapped__屬性。感謝指針,它可以與我的示例應用程序一起工作。 –