[英]Decorator / wrapper around python class attribute
I am trying to enhance the default @property
behavior in Python:我正在尝试增强 Python 中的默认@property
行为:
from functools import wraps
def MyProperty(func):
def getter(self):
"""Enhance the property"""
return func(self) + 1
return property(getter)
class MyClass(object):
def __init__(self, foo):
self._foo = foo
@MyProperty
def foo(self):
return self._foo
This all works very fine, I get the desired effect这一切都很好,我得到了想要的效果
A = MyClass(5)
A.foo
>>> 6
Since I have learned it that way, I want to apply the wraps
decorator to the wrapper for good-practice reasons.由于我是这样学习的,出于良好实践的原因,我想将wraps
装饰器应用于包装器。 But if I do write the wrapper as但是,如果我确实将包装器写为
def MyProperty(func):
@wraps
def getter(self):
"""Enhance the property"""
return func(self) + 1
return property(getter)
I now get我现在得到
A = MyClass(5)
A.foo
>>> <__main__.MyClass object at 0x7f209f4aa0d0>
Which is not what I expect.这不是我所期望的。 Any suggestions?有什么建议么?
Use this:用这个:
def MyProperty(func):
@wraps(func)
def getter(self):
"""Enhance the property"""
return func(self) + 1
return property(getter)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.