关于如何在python中使用属性功能的真实示例? [英] Real world example about how to use property feature in python?
问题描述
我对如何在Python中使用@property
感兴趣.我已经阅读了python文档,并认为其中的示例只是一个玩具代码:
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
有什么好处.为什么不只是实现为:
class C(object):
def __init__(self):
self.x = None
我认为,属性功能在某些情况下可能很有用.但当?有人可以给我一些真实的例子吗?
谢谢.
其他示例将是对设置属性的验证/过滤(强制将它们限制在可接受范围内)以及对复杂或快速变化的术语进行惰性评估.>
隐藏在属性后面的复杂计算:
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
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
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?
Thanks.
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
Validation:
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屋!