且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用于getter和setter的Google样式指南属性

更新时间:2023-09-30 16:56:58

在样式指南中,他们确实给出了原因:

In the style guide they do give a reason:

如果不覆盖属性本身,则具有属性的继承可以是非显而易见的.因此,必须确保间接调用访问器方法,以确保属性(使用模板方法DP)调用子类中重写的方法.

Inheritance with properties can be non-obvious if the property itself is not overridden. Thus one must make sure that accessor methods are called indirectly to ensure methods overridden in subclasses are called by the property (using the Template Method DP).

(其中模板方法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中添加了gettersetterdeleter装饰器属性.样式指南必须是针对较旧的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.