有人可以解释在Python中对象名称之前有前导下划线的确切含义吗?另外,解释单个和双重前导下划线之间的区别.此外,无论所讨论的对象是变量,函数,方法等,这个含义是否保持不变?
Python使我们能够通过在名称前加上双下划线来在类中创建"私有"方法和变量,如下所示:__myPrivateMethod().那么,如何解释这一点呢
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
Run Code Online (Sandbox Code Playgroud)
这是怎么回事?!
我会对那些没有那么做的人解释一下.
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
Run Code Online (Sandbox Code Playgroud)
我在那里做的是使用公共方法和私有方法创建一个类并实例化它.
接下来,我称之为公共方法.
>>> obj.myPublicMethod() …Run Code Online (Sandbox Code Playgroud) 如何在受保护的python类中定义一个方法,只有子类可以看到它?
这是我的代码:
class BaseType(Model):
def __init__(self):
Model.__init__(self, self.__defaults())
def __defaults(self):
return {'name': {},
'readonly': {},
'constraints': {'value': UniqueMap()},
'cType': {}
}
cType = property(lambda self: self.getAttribute("cType"), lambda self, data: self.setAttribute('cType', data))
name = property(lambda self: self.getAttribute("name"), lambda self, data: self.setAttribute('name', data))
readonly = property(lambda self: self.getAttribute("readonly"),
lambda self, data: self.setAttribute('readonly', data))
constraints = property(lambda self: self.getAttribute("constraints"))
def getJsCode(self):
pass
def getCsCode(self):
pass
def generateCsCode(self, template=None, constraintMap=None, **kwargs):
if not template:
template = self.csTemplate
if not constraintMap: constraintMap …Run Code Online (Sandbox Code Playgroud) 当我在私有变量链接上阅读python文档时,我有一个问题.
因此,文档说明使用下划线命名私有变量是一种约定,但python不会使该字段为私有.
>>> class a():
def __init__(self):
self.public = 11
self._priv = 12
>>> b = a()
>>> print b._priv
>>> 12
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一种方法可以在python中使变量"真正"私有.