【python】详解类class的访问控制:单下划线_与双下划线__(四)

Python中没有访问控制的关键字,例如private、protected等等。但是,在Python编码中,有一些约定来进行访问控制。

1、单下划线"_"

  • 在Python中,通过单下划线"“来实现模块级别的私有化,变量除外。一般约定以单下划线”"开头的函数为模块私有的,也就是说"from moduleName import * “将不会引入以单下划线”_"开头的函数。

现在有一个模块 example_example.py,内容用如下,模块中一个变量名和一个函数名分别以"_"开头:

name = 'bruce'
_tall = 180

def call_for():
    print('name is :',name)
    print('_tall is',_tall)
    
def _call_for():
    print('name is :',name)
    
#_call_for = _call_for()    
print()
print('_tall is',_tall)

运行脚本输出:


_tall is 180

再次调用该脚本:

#调用脚本模块example_example
import example_example
#调用不带下划线变量
example_example.name
Out[12]: 'bruce'
#调用带下划线变量
example_example._tall     #对于变量单下划线不会影响调用
Out[13]: 180
#调用不带下划线函数
example_example.call_for()
name is : bruce
_tall is 180
#调用不带下划线函数会报错
example_example._call_for()
Traceback (most recent call last):

  File "", line 1, in 
    example_example._call_for()

TypeError: 'NoneType' object is not callable

2、双下划线"__"

  • 对于Python中的类属性,可以通过双下划线"__“来实现一定程度的私有化,因为双下划线开头的属性在运行时会被"混淆”(mangling)。
class person(object):
    
    tall = 180
    hobbies = []
    def __init__(self, name, age,weight):
        self.name = name
        self.age = age
        self.weight = weight
        self.__Id = 430
    @staticmethod
    def infoma():
        print(person.tall)
        print(person.hobbies)
#person.infoma()
Bruce = person("Bruce", 25,180)
print(Bruce.__Id)
#Bruce.infoma() 

运行程序输出:

Traceback (most recent call last):

  File "", line 1, in 
    runfile('C:/Users/BruceWong/.spyder-py3/类的定义构建.py', wdir='C:/Users/BruceWong/.spyder-py3')

  File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)

  File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/BruceWong/.spyder-py3/类的定义构建.py", line 166, in 
    print(Bruce.__Id)

AttributeError: 'person' object has no attribute '__Id'

其实,通过内建函数dir()就可以看到其中的一些原由,"__Id"属性在运行时,属性名被改为了"_person__Id"(属性名前增加了单下划线和类名

print(dir(Bruce))
#可以看到Bruce中有_person__Id的属性,相较原__Id属性,变得可调用
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_person__Id', 'age', 'hobbies', 'infoma', 'name', 'tall', 'weight']

所以说,即使是双下划线,也没有实现属性的私有化,因为通过下面的方式还是可以直接访问"__Id"属性:

class person(object):
    
    tall = 180
    hobbies = []
    def __init__(self, name, age,weight):
        self.name = name
        self.age = age
        self.weight = weight
        self.__Id = 430     #############
    @staticmethod
    def infoma():
        print(person.tall)
        print(person.hobbies)
#person.infoma()
Bruce = person("Bruce", 25,180)
print(Bruce._person__Id)
#Bruce.infoma()  

输出运行结果:

430  #通过使属性__Id名前增加了单下划线_和类名person来实现属性的可调用
  • 双下划线的另一个重要的目地是,避免子类对父类同名属性的冲突
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()

当实例化B的时候,由于没有定义_ _ init_ 函数,将调用父类的 _ init_ _,但是由于双下划线的"混淆"效果,"self.__private()"将变成 “self._A__private()”。

总结:
"__“和” _ __"的使用 更多的是一种规范/约定,并没有真正达到限制的目的:

  • “_”:以单下划线开头的表示的是protected类型的变量,即只能允许其本身与子类进行访问;同时表示弱内部变量标示,如,当使用"from moduleNmae import *"时,不会将以一个下划线开头的对象引入。
  • “__”:双下划线的表示的是私有类型的变量。只能是允许这个类本身进行访问了,连子类也不可以,这类属性在运行时属性名会加上单下划线和类名

你可能感兴趣的:(python)