您的位置:首页 > 编程语言 > Python开发

Python public private

2016-04-06 19:55 671 查看
1. object # public

2. __object__ # special, python system use, user should not define like it

3. __object # private (name mangling during runtime)

4. _object # obey python coding convention, consider it as private

python有关private的描述,python中不存在protected的概念,要么是public要么就是private,但是python中的private不像C++, Java那样,它并不是真正意义上的private,通过name mangling(名称改编(目的就是以防子类意外重写基类的方法或者属性),即前面加上“单下划线”+类名,eg:_Class__object)机制就可以访问private了。

1.class Foo():

2. def __init__():

3. ...

4.

5. def public_method():

6. print 'This is public method'

7.

8. def __fullprivate_method():

9. print 'This is double underscore leading method'

10.

11. def _halfprivate_method():

12. print 'This is one underscore leading method'

实例化Foo的一个对象,

1. f = Foo()

1. f.public_method() # OK

2.

3. f.__fullprivate_method() # Error occur

4.

5. f._halfprivate_method() # OK

6.

7. f._Foo__fullprivate()_method() # OK

class A(object):
def __init__(self):
self.__private()
self.public()
def __private(self):
print 'A.__private()'
def public(self):
print 'A.public()'
class B(A):
def __private(self):
print 'B.__private()'
def public(self):
print 'B.public()'
b = B()
初探
正确的答案是:
A.__private()
B.public()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: