python - Python 中的@property 速度开销

标签 python performance properties object-design

<分区>

我正在尝试了解 Python 中 @property 装饰器的实用性。具体来说,我使用如下属性设置了一个类:

class A(object):
    def __init__(self, x):
        self._x = x

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, new_x):
        self._x = new_x

我还设置了一个没有提供相同功能的属性的类:

class B(object):
    def __init__(self, x):
        self._x = x

我为每个创建了一个实例:

a = A(10)
b = B(10)

在 iPython 中运行 %timeit 产生以下结果

%timeit a.x
%timeit b._x

1000000 次循环,最好的 3 次:每次循环 213 ns

10000000 次循环,3 次最佳:每次循环 67.9 ns

%timeit a.x = 15
%timeit b._x = 15

1000000 次循环,最好的 3 次:每次循环 257 纳秒

10000000 次循环,最好的 3 次:每次循环 89.7 ns

很明显,如果您要频繁地与对象对话,@property 和@setter 装饰器就比较差了。我的问题很简单,为什么要使用它?我很想听听人们可能拥有的这些装饰器的任何用例。谢谢。

最佳答案

简单的答案是您不使用 property 作为基本属性。它们对于在存储或检索时需要额外逻辑的属性很有用。例如,具有从其他属性派生的值的属性或需要错误检查或其他专门过滤的属性。使用 property 可以让您在单点菜单中使用在其他语言中常见的常见 setter/getter 模式,以时尚而不是强制使用冗长的样板。

关于python - Python 中的@property 速度开销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21174590/

相关文章:

c++ - 有人对 FastDB(C++ 内存数据库)有任何经验吗?

javascript - Object.create( parentObject{ nestedObject :{} } )

c# - 只读自动实现的属性是否可能?

python - "module.__init__() takes at most 2 arguments (3 given)"创建子类实例时

python - 将 .py 转换为 HTML

python - 索引超出尺寸 100 的轴 0 的范围

python - 有没有办法提高 nltk.sentiment.vader 情感分析的性能?

ASP.net 站点 : Long-loading page for user puts all other page loads for user on Hold

python - 使用 Python 的变量文件

python - 在 Python 中调用时或在 __init__ 中初始化属性