Python private函数使用疑惑,pythonprivate,>>> class My


>>> class MyClass:            def PublicMethod(self):                print 'public method'        def __PrivateMethod(self):               print 'this is private!'>>> obj = MyClass()>>> obj.PublicMethod()public method>>> obj.__PrivateMethod()Traceback (most recent call last):  File "", line 1, in AttributeError: MyClass instance has no attribute '__PrivateMethod'>>> dir(obj)['_MyClass__PrivateMethod', '__doc__', '__module__', 'PublicMethod']>>> obj._MyClass__PrivateMethod()this is private!

如上的执行,为什么到了 obj.__PrivateMethod() 就会出错,为何会这样?

既然是 Private ,你从类外部访问当然不存在(出错)了。

>>> class MyClass:        def PublicMethod(self):            print 'public method'    def __PrivateMethod(self):           print 'this is private!'    def callPrivateMethod(self):           self.__PrivateMethod()

在类自己的方法就能访问到。

当然,正如你看到,它只是被改了一个名字,即它只是一个语法糖罢了。

Python类的私有变量和私有方法是以“__”开头的,如果在类中有双下线开头,那么就是私有的。
生成实例时,访问不到,要在变量或方法前加_class name才可以访问。
例:

class A:    def __init__(self):        self.__b = 1        self.c = 2    def __d(self):        print 'method d'

print dir(A)
得到:['_A__d', 'doc', 'init', 'module']
也得就其实访问私有的变量和方法时,会在其前面加_A。

额...能从外部访问的话它还能叫私有函数么...另外,似乎这个链接可以帮你答疑解惑:http://stackoverflow.com/questions/1547145/defining-private-module-functions-in-python

既然是 Private ,你从类外部访问当然不存在(出错)了。

>>> class MyClass:        def PublicMethod(self):            print 'public method'    def __PrivateMethod(self):           print 'this is private!'    def callPrivateMethod(self):           self.__PrivateMethod()

在类自己的方法就能访问到。

当然,正如你看到,它只是被改了一个名字,即它只是一个语法糖罢了。

编橙之家文章,

评论关闭