python 支持私有变量吗?
Does python support private variables?
我听说 Python 中不存在“只能从对象内部访问的“私有”实例变量:as seen here
但是,我们可以在 python 中使用 getter 和 setter 方法创建私有变量,如下所示
class C(object):
def getx(self):
return self._x
def setx(self, value):
self._x = value
x = property(fset=setx)
c = C()
c.x = 2
print c.x
当我尝试访问 c.x 时,出现如下错误:
Traceback (most recent call last):
File "d.py", line 12, in <module>
print c.x
AttributeError: unreadable attribute
c.x 不可访问这一事实是否意味着 x 的行为类似于私有变量?这个事实与上面 link 中所说的有什么关系?
有很多关于这个主题的文献,但简而言之:
Python 与实际上具有 "private" 属性的编程语言不同,因为其他函数无法真正访问任何属性。是的,我们可以使用 property
模拟 Java 等语言的行为,正如您所展示的那样,但这是一种捏造 "true" 私有属性。 property
实际上是一个 higher-order 函数(好吧,从技术上讲,它是一个装饰器),所以当你调用 c.x
时,尽管它充当 属性,你实际上指的是一个控制你是否可以使用其中定义的 getters 和 setters 的函数。
但仅仅因为 c.x
不允许直接读取访问,并不意味着您不能调用 print c._x
(正如@avigil 指出的那样)。所以 c._x
并不是真正的私有 - 它与属于 C
class 的任何其他属性一样容易访问。它的名称以下划线开头的事实只是一种约定 - 向其他程序员发出的信号:"Please don't handle this variable directly, and use the getters/setters instead"(如果可用)。
是的,Python支持私有变量。
您可以在 class 中声明一个私有变量,如下所示:
__variableName = someValue
双下划线 (__) 后跟一个变量和一些赋值。
下面的示例将帮助您了解私有变量的可访问性:
class Book:
publisher = 'xyz' #public variable
_comm = 12.5 #protected variable
__printingCost = 7 #private variable
def printPriVar(self):
print(self.__printingCost)
b = Book()
print(b.publisher)
print(b._comm)
#print(Book.__printingCost) #Error
#print(b.__printingCost) #Error
我听说 Python 中不存在“只能从对象内部访问的“私有”实例变量:as seen here
但是,我们可以在 python 中使用 getter 和 setter 方法创建私有变量,如下所示
class C(object):
def getx(self):
return self._x
def setx(self, value):
self._x = value
x = property(fset=setx)
c = C()
c.x = 2
print c.x
当我尝试访问 c.x 时,出现如下错误:
Traceback (most recent call last):
File "d.py", line 12, in <module>
print c.x
AttributeError: unreadable attribute
c.x 不可访问这一事实是否意味着 x 的行为类似于私有变量?这个事实与上面 link 中所说的有什么关系?
有很多关于这个主题的文献,但简而言之:
Python 与实际上具有 "private" 属性的编程语言不同,因为其他函数无法真正访问任何属性。是的,我们可以使用 property
模拟 Java 等语言的行为,正如您所展示的那样,但这是一种捏造 "true" 私有属性。 property
实际上是一个 higher-order 函数(好吧,从技术上讲,它是一个装饰器),所以当你调用 c.x
时,尽管它充当 属性,你实际上指的是一个控制你是否可以使用其中定义的 getters 和 setters 的函数。
但仅仅因为 c.x
不允许直接读取访问,并不意味着您不能调用 print c._x
(正如@avigil 指出的那样)。所以 c._x
并不是真正的私有 - 它与属于 C
class 的任何其他属性一样容易访问。它的名称以下划线开头的事实只是一种约定 - 向其他程序员发出的信号:"Please don't handle this variable directly, and use the getters/setters instead"(如果可用)。
是的,Python支持私有变量。 您可以在 class 中声明一个私有变量,如下所示:
__variableName = someValue
双下划线 (__) 后跟一个变量和一些赋值。 下面的示例将帮助您了解私有变量的可访问性:
class Book:
publisher = 'xyz' #public variable
_comm = 12.5 #protected variable
__printingCost = 7 #private variable
def printPriVar(self):
print(self.__printingCost)
b = Book()
print(b.publisher)
print(b._comm)
#print(Book.__printingCost) #Error
#print(b.__printingCost) #Error