由于从技术上讲属性在 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
当然,您可能仍然使用 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 classname
in which __attr
is defined, __attr
is 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 private
modifier does.
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.