Python Get function parent attribute
I have a function in python that return an inn开发者_开发知识库er function
def parent_func(func):
def decorator(a,b):
return a + b
return decorator
for simplify lets consider this code
def in_func ( a, b)
return a*b
child = parent_func ( in_func)
Does someone know a way to get the "func" attribute of parent_func from child?
The func
attribute only exists in the scope of the parent_func()
function.
If you really need that value, you can expose it:
def parent_func(func):
def decorator(a,b):
return a + b
decorator.original_function = func
return decorator
Next question is, why would you want to do that? What is the actual design problem behind this issue?
You can store it as an attribute on decorator
before returning it.
>>> def parent_func(func):
... def decorator(a,b):
... return a + b
... decorator.func = func
... return decorator
...
>>> @parent_func
... def product(a, b):
... return a * b
...
>>> product.func
<function product at 0x000000000274BD48>
>>> product(1, 1)
2
You are slightly misusing decorators here. What is the point of writing a decorator which completely ignores the original function it is given?
Oh, I've also used the @foo
decorator syntax, because it's cleaner. It's equivalent to what you have written, though.
精彩评论