封装:将对象的状态信息隐藏在对象内部,不允许外部程序直接访问对象内部信息,而是通过该类提供的方法实现对内部信息的操作和访问;
作用:
让使用者只能通过事先预定的方法访问实例参数,从而可以在该方法中加入控制逻辑,限制对属性的不合理访问;
隐藏类的实现细节;
Python并没有提供类似于其他语言的private等修饰符,因此Python不能真正实现隐藏;
为了隐藏类中的成员,只要将Python类的成员命名以双下划线开头,Python就会将他们“隐藏”起来,如下代码所示:
# 定义一个矩形类
class Rectangle:
def __init__(self, width, height):
self.__width = width
self.__height = height
def getWidth(self):
return self.__width
# 创建一个对象
my_rectangle = Rectangle(10, 5)
print(my_rectangle.__width)
# 程序报错,AttributeError: 'Rectangle' object has no attribute '__width'
我们将实例变量命名为__width,然后在程序中调用发现程序报错“类Rectangle对象没有属性__width”,原因是因为python将该变量隐藏了,这样程序就无法直接访问__width变量,只能通过getWidth()方法访问;
但这个“隐藏”不是真正意义上的隐藏,这只是Python的一个“易容术”,Python会“偷偷”改变以双下划线开头的方法名,会在这些方法名前添加单下划线和类名,因此可以对“隐藏”的变量这样访问:
# 定义一个矩形类
class Rectangle:
def __init__(self, width, height):
self.__width = width
self.__height = height
def getWidth(self):
return self.__width
# 创建一个对象
my_rectangle = Rectangle(10, 5)
print(my_rectangle._Rectangle__width)
# 10