【问题标题】:Should Python's property() be used as a decorator or saved to a variable?Python 的 property() 应该用作装饰器还是保存到变量中?
【发布时间】:2012-12-08 13:21:23
【问题描述】:

使用 Python 内置函数property() 的首选方式是什么?作为装饰器还是保存到变量中?

这是一个将property() 保存到变量color 的示例。

class Train(object):
    def __init__(self, color='black'):
        self._color = color

    def get_color(self):
        return self._color

    def set_color(self, color):
        self._color = color

    def del_color(self):
        del self._color
    color = property(get_color, set_color, del_color)

这是相同的示例,但使用了装饰器。

class Train(object):
    def __init__(self, color='black'):
        self._color = color

    @property
    def color(self):
        return self._color

    @color.setter
    def color(self, color):
        self._color = color

    @color.deleter
    def color(self):
        del self._color

我发现有些人喜欢对只读属性使用装饰器语法。例如。

class Train(object):
    def __init__(self, color='black'):
        self._color = color

    @property
    def color(self):
        return self._color

但保存到变量时也可以实现相同的功能。

class Train(object):
    def __init__(self, color='black'):
        self._color = color

    def get_color(self):
        return self._color
    color = property(get_color)

自从PEP20 声明以来,相同功能的两种方式让我感到困惑

应该有一种——最好只有一种——明显的方法。

【问题讨论】:

  • 我更喜欢装饰器语法,因为它不会创建永远不应调用的额外方法(但直接调用 property() 函数会)我不确定这是否是官方首选的方法.
  • 有两种方法的原因是直到 Python 2.4 才引入装饰器,所以在此之前,您的第一个示例是唯一的方法。装饰器允许更易读的代码,但旧方法仍然可行。
  • 感谢@Matt 解释装饰器保护方法,因此它们不能像Train().color('green') 那样被调用。从现在开始,我将一直使用装饰器。 :)

标签: python properties decorator


【解决方案1】:

从功能上讲,这两种方法是等效的。装饰器语法只是语法糖。

@some_decorator
def some_func():
    ...

...等价于...

def some_func():
    ....
some_func = some_decorator(some_func)

装饰器语法使您的代码更干净(非装饰器语法意味着您必须键入“some_func”三遍!)并且您的意图更明显,所以我会说绝对使用装饰器语法。

【讨论】:

  • 谢谢@tom!从现在开始我只会使用装饰器。不过有一条评论,非装饰器语法可以(并且是recommended)写在一个衬里。例如color = property(get_color, set_color, del_color)
  • 是的,关于:单线。但是在非装饰器语法中,您仍然需要键入 [color, get_color, set_color, del_color] 两次,而在装饰器语法中,您只需键入一次。
猜你喜欢
  • 1970-01-01
  • 2016-03-14
  • 2018-02-03
  • 2017-01-25
  • 2021-05-15
  • 2022-11-29
  • 1970-01-01
相关资源
最近更新 更多