问题描述
在其中给出了以下示例:
In it, they give the following example:
class Square(object):
"""A square with two properties: a writable area and a read-only perimeter.
To use:
>>> sq = Square(3)
>>> sq.area
9
>>> sq.perimeter
12
>>> sq.area = 16
>>> sq.side
4
>>> sq.perimeter
16
"""
def __init__(self, side):
self.side = side
def __get_area(self):
"""Calculates the 'area' property."""
return self.side ** 2
def ___get_area(self):
"""Indirect accessor for 'area' property."""
return self.__get_area()
def __set_area(self, area):
"""Sets the 'area' property."""
self.side = math.sqrt(area)
def ___set_area(self, area):
"""Indirect setter for 'area' property."""
self.__set_area(area)
area = property(___get_area, ___set_area,
doc="""Gets or sets the area of the square.""")
@property
def perimeter(self):
return self.side * 4
对此我有两个问题:
-
与直接使用两个下划线相比,使用三个下划线间接"
___get_area
和___set_area
以及两个下划线有什么好处?
What is the benefit of using the three underscore "indirection"
___get_area
and___set_area
as well as two underscore ones, over just using the two underscore ones directly?
为什么将property()
用作具有这组双重和三次下划线方法的方法,而不是执行以下操作:
Why use property()
as a method with this set of double and triple underscore methods, rather than doing something like:
@property
def area(self):
return self.side ** 2
@area.setter
def area(self, value):
self.side = math.sqrt(value)
推荐答案
在样式指南中,他们确实给出了原因:
In the style guide they do give a reason:
(其中模板方法DP 是模板方法设计模式(Google的Pythonista非凡专家Alex Martelli的幻灯片).
(where Template Method DP is the Template Method Design Pattern (slides by Alex Martelli, Pythonista extraordinaire at Google).
因此,他们希望为子类提供重写实现的机会,并为property
提供三下划线版本来调用double-underscore方法,以便您可以重写这些方法.在这种情况下,您必须拼写错误的名称:
So they want to give subclasses the chance to override the implementation, and give the property
the triple-underscore versions to call the double-underscore methods so you can override these. You'd have to spell out the mangled name in that case:
class WonkySquare(Square):
def _Square__get_area(self):
return self.square ** 2 + 0.5
显然,提出此方案的人们从来不知道您只能覆盖属性的getter或setter,请参见:
Apparently the people that came up with this scheme never knew that you can override just a getter or setter of a property, see Python overriding getter without setter:
class ProperlySubclassedSquare(Square):
@Square.area.getter
def area(self):
return self.square ** 2 + (0.5 - 0.5)
然后,再次在Python 2.6中添加了getter
,setter
和deleter
装饰器属性.样式指南必须是针对较旧的Python版本编写的.
Then again, the getter
, setter
and deleter
decorator attributes were only added in Python 2.6. The style guide must've been written for an older Python version.
对于2.6及更高版本,请坚持使用@propname.setter
模式.
For 2.6 and up, stick to the @propname.setter
pattern instead.
这篇关于用于getter和setter的Google样式指南属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!