简体   繁体   English

Python 获取和设置方法与@property 装饰器

[英]Python get and set methods versus @property decorator

I am exploring decorators in Python, and as a person who came to Python from other languages, I am a bit confused about the purpose of @property and its @xxx.setter brother.我正在探索Python中的装饰器,作为一个从其他语言来到Python的人,我对@property及其@xxx.setter兄弟的目的有点困惑。 In Java and C++ get_xxx() and set_xxx() are usually the way to organize encapsulation.在 Java 和 C++ 中get_xxx()set_xxx()通常是组织封装的方式。 In Python we have these two decorators, which require specific syntax, and name matching in order to work.在 Python 中,我们有这两个装饰器,它们需要特定的语法和名称匹配才能工作。 How is @property better than get-set methods? @property如何比get-set方法更好?

I have checked this post and still, what are the advantages of @property besides the availability of the += operator?我已经检查了这篇文章,但除了+=运算符的可用性之外, @property的优点是什么?

The best part of using property for an attribute is that you don't need it .property用于属性的最佳部分是您不需要它

The philosophy in Python is that classes attributes and methods are all public, but by convention - when you prefix their name with a single "_" Python 中的理念是类属性和方法都是公共的,但按照惯例 - 当您在它们的名称前加上一个“_”

The mechanism behing "property", the descriptor protocol, allows one to change a previous dumb plain attribute into an instrumented attribute, guarded with code for the getter and setter, if the system evolves to a situation where it is needed. “属性”的机制,即描述符协议,允许人们将以前的愚蠢的普通属性更改为检测属性,如果系统发展到需要它的情况,则使用 getter 和 setter 的代码进行保护。

But by default, a name attribute in a class, is just a plain attribute.但默认情况下,class 中的name属性只是一个普通属性。 You do person.name = "Name" - no guards needed, no setting method needed nor recommended.你做person.name = "Name" - 不需要警卫,不需要也不推荐设置方法。 When and if it one needs a guard for that (say, to capitalize the name, or filter on improper words), whatever code uses that attribute needs no change: with the use of property, attribute assignment still takes place with the "=" operator.当它需要保护时(例如,将名称大写或过滤不正确的单词),无论使用该属性的代码都不需要更改:使用属性,属性分配仍然通过“=”进行操作员。

Other than that, if using "=" does not look prettier than person.set_name("Name") for you, I think it does for most people.除此之外,如果对您来说使用“=”看起来并不比person.set_name("Name")漂亮,我认为它对大多数人来说都是如此。 Of course, that is subjective.当然,这是主观的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM