Python中的访问控制

版权声明:版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/swinfans/article/details/84901482

Python中没有访问控制的关键字,例如 privateprotected 等。但是却有一些约定来进行访问控制。

  • 在模块中但不在类中的变量或函数,若变量名或函数名以单下划线开头,则该变量或函数为模块私有,通过 import module_name from * 的方式不会将这些变量或函数导入;

  • 在类定义体中的变量或方法,若其名称以单个下划线开头,则该变量或方法为 protected 类型;

  • 在类定义体中的变量或方法,若其名称以两个下划线开头但不以两个下划线结束,则该变量或方法为 private 类型;在类定义体外,无法类名或实例名直接访问。

我们通过以下几个例子来进行说明:

01

创建一个名称为 examples.py 的文件,内容如下:

name = 'bossen'
_name = 'neo'

def get_name():
	print('name is', name)

def _get_name():
	print('name is', _name)

进入python的交互模式:

>>> from examples import *
>>> name
'bossen'
>>> _name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_name' is not defined
>>> get_name()
name is bossen
>>> _get_name()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_get_name' is not defined

可以看到,当访问模块 examples 中的变量 _name_get_name() 时均提示未定义。

02

>>> class Employee:
...     _department = 'SQA'
...     __title = 'employee'
...     @staticmethod
...     def _test_protected():
...         return 'this is a protected method'
...     @staticmethod
...     def __test_private():
...         return 'this is a private method'
... 
>>> e = Employee()
>>> e._department
'SQA'
>>> e.__title
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Employee' object has no attribute '__title'
>>> e._test_protected()
'this is a protected method'
>>> e._test_private()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Employee' object has no attribute '_test_private'
>>> 

可以看到,试图访问类中的私有变量时,均提示 Employee 类没有对应的属性。

03

但是,是否就真的无法访问这些 private 类型的变量或者方法了呢? 答案是否定的。
要访问类的私有属性,必须在要访问的属性的名称前加上 _className 前缀,其中 className 为类名。如下例所示:

>>> e._Employee__title
'employee'
>>> e._Employee__test_private()
'this is a private method'
>>> 

可以看到,通过这种方式,就可以访问类中的私有属性了。

猜你喜欢

转载自blog.csdn.net/swinfans/article/details/84901482