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
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()
相关文章推荐
- scrapy爬取智联招聘中python工程师的招聘信息
- 2048游戏python版
- Python循环语句
- Python 资源大全
- python学习2
- python小模块---zipfile
- Python 求解斐波那切(三种方法)
- Python 使用xlrd库读取excel
- Python LOGGING使用方法
- python去除列表中重复的元素
- 压缩感知重构算法之IRLS算法python实现
- Python自然语言处理:词干、词形与MaxMatch算法
- python 访问 zookeeper
- python 访问 zookeeper
- Android 上多方式定位元素(python)
- numpy 学习,里面有converters参数的使用方法
- python为什么有私有方法和变量
- Python str方法总结
- python学习1
- Python -- 使用os.remove删除文件夹时报错