应用装饰器的弃用

7 投票
3 回答
1916 浏览
提问于 2025-04-15 20:00

之前有一种很好的方法,可以在一个函数里组织类的属性,使用的是apply装饰器。

class Example(object):
    @apply
    def myattr():
        doc = """This is the doc string."""

        def fget(self):
            return self._half * 2

        def fset(self, value):
            self._half = value / 2

        def fdel(self):
            del self._half

        return property(**locals())

但是现在apply已经被弃用了。

有没有可能用新的“扩展调用语法”来实现同样简单易读的属性组织方式呢?


我的方法和Anurag的差不多,但我不知道哪个更好,请看一下:

def prop(f):

    return property(**f())

class A(object):

    @prop
    def myattr():

        def fget(self):
            return self._myattr

        def fset(self, value):
            self._myattr = value 

        return locals()

3 个回答

0

你可以随时自己写一个:

def apply(f, a):
    return f(*a)

不过,我不太明白以这种方式使用 apply 作为装饰器有什么好处。它的用途是什么呢?

2

:) 这个人用 apply 的方法真聪明,不过我不太确定这样做有没有什么问题。

不管怎样,你可以这样做:

class Example(object):
    def myattr():
        doc = """This is the doc string."""

        def fget(self):
            return self._half * 2

        def fset(self, value):
            self._half = value / 2

        def fdel(self):
            del self._half

        return property(**locals())
    myattr = myattr()
12

有没有可能让属性的写法变得这么简单和易读呢?

在Python 2.6中,可以这样做:

@property
def myattr(self):
    """This is the doc string."""
    return self._half * 2

@myattr.setter
def myattr(self, value):
    self._half = value / 2

@myattr.deleter
def myattr(self):
    del self._half

撰写回答