申请装饰者的弃用

Vad*_* P. 7 python

通过使用apply decorator,有一种漂亮的方法可以在一个函数的框架中组织类属性.

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())
Run Code Online (Sandbox Code Playgroud)

但现在申请已被弃用.

是否有可能实现属性的这种简单性和可读性,使用new,而不是"扩展调用语法"?


我的方法与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()
Run Code Online (Sandbox Code Playgroud)

bob*_*nce 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
Run Code Online (Sandbox Code Playgroud)

  • 我不知道这一点,我很喜欢它.上面的"应用"魔法是如此难以理解,我不太清楚问题是关于什么的.我知道@property并且使用它很多,但.setter和.deleter对我来说很新,看起来很棒(自我记录代码):) (3认同)
  • @JacekKonieczny - 你错了,@ apply的这种用法是可读的,只要你知道关于装饰器和高阶函数(比如`apply`)的一两件事.更有用的是在Python中使用闭包的简单而优雅的方式 - 你知道,在OP发布的示例中,你可以引入一些由getter/setter/deleter函数共享的变量,这些变量将是真正的私有,并且不会污染类的命名空间!只是用你的想象力而不是拒绝你还不知道的事情. (2认同)