关于如何在python中使用属性功能的真实世界示例? [英] Real world example about how to use property feature in python?
问题描述
我对如何在 Python 中使用 @property
感兴趣.我已经阅读了 python 文档,在我看来,那里的示例只是一个玩具代码:
I am interested in how to use @property
in Python. I've read the python docs and the example there, in my opinion, is just a toy code:
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
我不知道包装充满属性装饰器的 _x
可以获得什么好处.为什么不直接实现为:
I do not know what benefit(s) I can get from wrapping the _x
filled with the property decorator. Why not just implement as:
class C(object):
def __init__(self):
self.x = None
我认为,属性功能在某些情况下可能很有用.但当?有人可以给我一些真实世界的例子吗?
I think, the property feature might be useful in some situations. But when? Could someone please give me some real-world examples?
推荐答案
其他示例包括验证/过滤设置的属性(强制它们在界限内或可接受范围内)以及对复杂或快速变化的术语进行惰性评估.
Other examples would be validation/filtering of the set attributes (forcing them to be in bounds or acceptable) and lazy evaluation of complex or rapidly changing terms.
>
隐藏在属性后面的复杂计算:
Complex calculation hidden behind an attribute:
class PDB_Calculator(object):
...
@property
def protein_folding_angle(self):
# number crunching, remote server calls, etc
# all results in an angle set in 'some_angle'
# It could also reference a cache, remote or otherwise,
# that holds the latest value for this angle
return some_angle
>>> f = PDB_Calculator()
>>> angle = f.protein_folding_angle
>>> angle
44.33276
验证:
class Pedometer(object)
...
@property
def stride_length(self):
return self._stride_length
@stride_length.setter
def stride_length(self, value):
if value > 10:
raise ValueError("This pedometer is based on the human stride - a stride length above 10m is not supported")
else:
self._stride_length = value
这篇关于关于如何在python中使用属性功能的真实世界示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!