Python的property()应该用作修饰符还是保存到变量中?

2024-04-20 05:24:24 发布

您现在位置:Python中文网/ 问答频道 /正文

使用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)

这里有一个相同的例子,但是使用了decorator。在

^{pr2}$

我发现有些人喜欢将decorator语法用于只读属性。例如。在

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声明

There should be one-- and preferably only one --obvious way to do it.


Tags: selfgetreturnobjectinitdeftraindecorator
1条回答
网友
1楼 · 发布于 2024-04-20 05:24:24

在功能上,这两种方法是等价的。decorator语法只是语法糖。在

@some_decorator
def some_func():
    ...

…相当于。。。在

^{pr2}$

decorator语法使您的代码更加简洁(非decorator语法意味着您必须键入“some\u func”三次!)而且你的意图更明显,所以我肯定要使用decorator语法。在

相关问题 更多 >