python私有方法和私有属性属性理解,子类继承

私有属性、方法——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']               

 

  • 私有的属性,不能通过对象直接访问,但是可以通过方法访问
  • 私有的方法,不能通过对象直接访问
  • 私有的属性、方法,不会被子类继承,也不能被访问
  • 一般情况下,私有的属性、方法都是不对外公布的,往往用来做内部的事情,起到安全的作用
  • 可以通过调用继承的父类的共有方法,间接的访问父类的私有方法、属性
posted @ 2017-11-05 13:40  mlj0503  阅读(15658)  评论(1编辑  收藏  举报