python类属性的装饰器/包装器

2024-04-26 00:38:13 发布

您现在位置: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

这一切都很好,我得到了理想的效果

A = MyClass(5)
A.foo
>>> 6

由于我是这样学习的,出于良好实践的原因,我想将wraps装饰器应用于包装器。但是如果我把包装纸写成

def MyProperty(func):
    @wraps
    def getter(self):
        """Enhance the property"""
        return func(self) + 1

    return property(getter)

我现在明白了

A = MyClass(5)
A.foo
>>> <__main__.MyClass object at 0x7f209f4aa0d0>

这不是我所期望的。有什么建议吗


Tags: thefromselfreturnobjectfoodefmyclass