问题描述
在 Python 中,我有以下示例类:
In Python, I have the following example class :
class Foo:
self._attr = 0
@property
def attr(self):
return self._attr
@attr.setter
def attr(self, value):
self._attr = value
@attr.deleter
def attr(self):
del self._attr
如您所见,我有一个简单的私有"属性_attr"和一个可以访问它的属性.有很多代码可以声明一个简单的私有属性,我认为这样声明所有属性是不尊重KISS"哲学的.
As you can see, I have a simple "private" attribute "_attr" and a property to access it. There is a lot of codes to declare a simple private attribute and I think that it's not respecting the "KISS" philosophy to declare all attributes like that.
那么,如果我不需要特定的 getter/setter/deleter,为什么不将我的所有属性声明为公共属性?
So, why not declare all my attributes as public attributes if I don't need a particular getter/setter/deleter ?
我的回答是:因为封装原理(OOP)另有说明!
My answer will be :Because the principle of encapsulation (OOP) says otherwise!
最好的方法是什么?
推荐答案
通常,Python 代码努力遵守 统一访问原则.具体来说,可接受的方法是:
Typically, Python code strives to adhere to the Uniform Access Principle. Specifically, the accepted approach is:
- 直接公开您的实例变量,例如允许
foo.x = 0
,而不是foo.set_x(0)
- 如果您需要将访问包装在方法中,无论出于何种原因,请使用
@property
,它保留了访问语义.也就是说,foo.x = 0
现在调用foo.set_x(0)
.
- Expose your instance variables directly, allowing, for instance,
foo.x = 0
, notfoo.set_x(0)
- If you need to wrap the accesses inside methods, for whatever reason, use
@property
, which preserves the access semantics. That is,foo.x = 0
now invokesfoo.set_x(0)
.
这种方法的主要优点是调用者可以这样做:
The main advantage to this approach is that the caller gets to do this:
foo.x += 1
即使代码可能真的在做:
even though the code might really be doing:
foo.set_x(foo.get_x() + 1)
第一条语句更具可读性.然而,通过属性,您可以(在开始时或稍后)添加通过第二种方法获得的访问控制.
The first statement is infinitely more readable. Yet, with properties, you can add (at the beginning, or later on) the access control you get with the second approach.
还要注意,以单个下划线开头的实例变量传统上是私有的.也就是说,下划线向其他开发人员发出信号,表明您认为该值是私有的,他们不应该直接弄乱它;然而,语言中没有任何内容阻止他们直接使用它.
Note, too, that instance variables starting with a single underscore are conventionally private. That is, the underscore signals to other developers that you consider the value to be private, and they shouldn't mess with it directly; however, nothing in the language prevents them from messing with it directly.
如果您使用双前导下划线(例如,__x
),Python 会对名称进行一些混淆.然而,该变量仍然可以通过其混淆的名称从类外部访问.这不是真正的私人.它只是有点……更不透明.并且有反对使用双下划线的有效论据;一方面,它会使调试变得更加困难.
If you use a double leading underscore (e.g., __x
), Python does a little obfuscation of the name. The variable is still accessible from outside the class, via its obfuscated name, however. It's not truly private. It's just kind of ... more opaque. And there are valid arguments against using the double underscore; for one thing, it can make debugging more difficult.
这篇关于“公开"或“私人"Python 中的属性?什么是最好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!