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) 我正在阅读PEP 0008(样式指南),我注意到它建议使用self作为实例方法中的第一个参数,但cls是类方法中的第一个参数.
我已经使用并编写了几个类,但我从未遇到过类方法(嗯,一个将cls作为参数传递的方法).有人能告诉我一些例子吗?
谢谢!