在 Python 中使用访问器的正确方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15706935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way to use accessors in Python?
提问by lol
Is this how you would define a class "Car" with attribute "Speed" in Python? My background is in Java, and it seems one does not use get/set methods in Python.
这是您在 Python 中定义具有属性“Speed”的类“Car”的方式吗?我的背景是 Java,似乎没有在 Python 中使用 get/set 方法。
class Car(object):
def __init__(self):
self._speed = 100
@property
def speed(self):
return self._speed
@speed.setter
def speed(self, value):
self._speed = value
采纳答案by Martijn Pieters
In Python we generally avoidgetters and setters. Just have a .speedattribute:
在 Python 中,我们通常避免使用getter 和 setter。只要有一个.speed属性:
class Car(object):
speed = 0
def __init__(self):
self.speed = 100
See Python is not Javafor motivations and more pitfalls to avoid:
请参阅Python 不是 Java以了解动机和要避免的更多陷阱:
In Java, you have to use getters and setters because using public fields gives you no opportunity to go back and change your mind later to using getters and setters. So in Java, you might as well get the chore out of the way up front. In Python, this is silly, because you can start with a normal attribute and change your mind at any time, without affecting any clients of the class. So, don't write getters and setters.
在 Java 中,您必须使用 getter 和 setter,因为使用公共字段使您没有机会在以后改变主意使用 getter 和 setter。因此,在 Java 中,您最好先将繁琐的工作排除在外。在 Python 中,这很愚蠢,因为您可以从一个普通属性开始并随时改变主意,而不会影响该类的任何客户端。所以,不要写 getter 和 setter。
Use propertywhen you have a genuine need to execute code when getting, setting or deleting an attribute. Validation, caching, side effects, etc. all are fair use-cases for properties. Just don't use them until necessary.
使用property时,你有真正需要时获取,设置或删除属性来执行代码。验证、缓存、副作用等都是属性的合理用例。除非必要,否则不要使用它们。
回答by lolopop
I would go for attributes, like that:
我会去寻找属性,就像这样:
class Car(object):
def __init__(self):
self.speed = 100
where you can change and get it exactly the same way. The @propertynotation is probably more of use for wrapping classes that use Java/C get/set methods, virtual attributes or if you need to manipulate the values being entered.
您可以在其中更改并以完全相同的方式获得它。该@property表示法可能更多地用于包装使用 Java/C get/set 方法、虚拟属性的类,或者如果您需要操作输入的值。
I use that often in GUI classes where I can easily force redrawing of the screen based on changing attributes of widgets, sort of a custom events system.
我经常在 GUI 类中使用它,在那里我可以根据小部件的更改属性轻松强制重绘屏幕,有点像自定义事件系统。
回答by Kyle Strand
Since technically attributes are never private in Python, get/set methods are not considered "pythonic." This is the standard way to access object attributes:
由于从技术上讲属性在 Python 中从来不是私有的,因此 get/set 方法不被视为“pythonic”。这是访问对象属性的标准方法:
class MyClass():
def __init__(self):
self.my_attr = 3
obj1 = MyClass()
print obj1.my_attr #will print 3
obj1.my_attr = 7
print obj1.my_attr #will print 7
You may, of course, still use getters and setters, and you can somewhat emulate private members by prepending __to your attributes:
当然,您仍然可以使用 getter 和 setter,并且您可以通过添加__到您的属性来模拟私有成员:
class MyClass():
def __init__(self):
self.__my_attr = 3
def set_my_attr(self,val):
self.__my_attr = val
def get_my_attr(self):
return self.__my_attr
obj1 = MyClass()
print obj1.get_my_attr() #will print 3
obj1.set_my_attr(7)
print obj1.get_my_attr() #will print 7
The __"mangles" the variable name: from outside some class classnamein which __attris defined, __attris renamed as _classname__attr; in the above example, instead of using the getters and setters, we could simply use obj1._MyClass__my_attr. So __discourages external use of attributes, but it doesn't prohibit it in the same way that the Java privatemodifier does.
的__“轧液机”的变量名:从某些类以外classname,其中__attr被定义,__attr被重命名为_classname__attr; 在上面的例子中,我们可以简单地使用obj1._MyClass__my_attr. 所以__不鼓励外部使用属性,但它不像 Javaprivate修饰符那样禁止它。
There are also, as you mention in your question, properties available in Python. The advantage of properties is that you can use them to implement functions that return or set values that, from outside the class, appear to be simply accessed as normal member attributes.
正如您在问题中提到的,Python 中还有可用的属性。属性的优点是您可以使用它们来实现从类外部返回或设置值的函数,这些值似乎只是作为普通成员属性访问的。

