4 私有化

 私有化

xx: 公有变量
_x: 单前置下划线,私有化属性或方法,from somemodule import *禁止导入,类对象和子类可以访问
__xx:双前置下划线,避免与子类中的属性命名冲突,无法在外部直接访问(名字重整所以访问不到)        #私有变量
__xx__:双前后下划线,用户名字空间的魔法对象或属性。例如:__init__ , __ 不要自己发明这样的名字
xx_:单后置下划线,用于避免与Python关键词的冲突             #if_ = 100

1.私有变量

class Dog(object):
    def __init__(self):
        self.__num = 100

dog1 = Dog()
print(dog1.__num)


### 不可以外部直接访问私有变量
python@ubuntu:~/02-就业班/02-高级-2$ python 01-私有变量.py 
Traceback (most recent call last):
  File "01-私有变量.py", line 6, in <module>
    print(dog1.__num)
AttributeError: 'Dog' object has no attribute '__num'
class Dog(object):
    def __init__(self):
        self.__num = 100
    def set_num(self):
        self.__num = 50
    def get_num(self):
        return self.__num

dog1 = Dog()
print(dog1.get_num())
dog1.set_num()
print(dog1.get_num())


### 通过实例方法调用私有属性
python@ubuntu:~/02-就业班/02-高级-2$ python3 01-私有变量.py 
100
50

 2._num    __num

    1)  from test import * #私有的不能通过导入模块后使用

###   test.py 
num = 10
_num = 20
__num = 40


In [1]: from test import *    #私有的不能通过导入模块后使用

In [2]: num
Out[2]: 10

In [3]: _num   
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-a3b2dccd37c6> in <module>()
----> 1 _num

NameError: name '_num' is not defined

In [4]: __num
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-560eb7fca2ba> in <module>()
----> 1 __num

NameError: name '__num' is not defined

   2)import test   #可以使用

In [1]: import test   #可以使用

In [2]: test.num
Out[2]: 10

In [3]: test._num
Out[3]: 20

In [4]: test.__num
Out[4]: 40

3.名字重整

通过name mangling(名字重整(目的就是以防子类意外重写基类的方法或者属性)如:_Class__object)机制就可以访问private了

In [5]: class Dog(object):
   ...:     def __init__(self):
   ...:         self.__num = 100
   ...:         

In [6]: t = Dog()

In [7]: dir(t)
Out[7]: 
['_Dog__num',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
In [8]: t._Dog__num
Out[8]: 100 

    

原文地址:https://www.cnblogs.com/venicid/p/7922840.html