首页 > 编程语言 > 详细

python私有方法和私有属性属性理解

时间:2017-11-05 14:17:12      阅读:332      评论:0      收藏:0      [点我收藏+]

私有属性、方法——Python并没有真正的私有化支持,但可用下划线得到伪私有
尽量避免定义以下划线开头的变量
   (1)_xxx      "单下划线 " 开始的成员变量叫做保护变量,意思是只有类对象(即类实例)和子类对象自己能访问到这些变量,需通过类提供的接口进行访问;不能用‘from module import *‘导入
   (2)__xxx    类中的私有变量/方法名 (Python的函数也是对象,所以成员方法称为成员变量也行得通。)," 双下划线 " 开始的是私有成员,意思是只有类对象自己能访问,连子类对象也不能访问到这个数据。
    (3)__xxx__ 系统定义名字,前后均有一个“双下划线” 代表python里特殊方法专用的标识,如 __init__() 代表类的构造函数。

In [6]: class Dog():
   ...:     def __sit_down(self):
   ...:         print(‘坐下了‘)
   ...:     def sit_down(self,host_name):
   ...:         if host_name==‘主人‘:
   ...:             self.__sit_down()

In [7]: w=Dog()

In [8]: w.sit_down(‘主人‘)
坐下了

In [9]: w.sit_down(‘主‘)

In [10]: w.__sit_down()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-16df8360e9bf> in <module>()
----> 1 w.__sit_down()

AttributeError: ‘Dog‘ object has no attribute ‘__sit_down‘

In [13]: w._Dog__sit_down()
坐下了

python实例可以直接调用Python的公有方法;私有方法和属性在外部不可以直接用属性或方法名调用,内部将私有方法和属性在前面增加了  "_类名"

                           
In [14]: dir(Dog)          
Out[14]:                   
[‘_Dog__sit_down‘,         
 ‘__class__‘,              
 ‘__delattr__‘,            
 ‘__dict__‘,               
 ‘__dir__‘,                
 ‘__doc__‘,                
 ‘__eq__‘,                 
 ‘__format__‘,             
 ‘__ge__‘,                 
 ‘__getattribute__‘,       
 ‘__gt__‘,                 
 ‘__hash__‘,               
 ‘__init__‘,               
 ‘__init_subclass__‘,      
 ‘__le__‘,                 
 ‘__lt__‘,                 
 ‘__module__‘,             
 ‘__ne__‘,                 
 ‘__new__‘,                
 ‘__reduce__‘,             
 ‘__reduce_ex__‘,          
 ‘__repr__‘,               
 ‘__setattr__‘,            
 ‘__sizeof__‘,             
 ‘__str__‘,                
 ‘__subclasshook__‘,       
 ‘__weakref__‘,            
 ‘sit_down‘]               

 

python私有方法和私有属性属性理解

原文:http://www.cnblogs.com/maxiaohei/p/7787256.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!