封装特性
什么是封装?
在日常中封装指的是将我们的物品包裹起来,不让看到其内部,具有保护的功能。在程序设计中,封装(Encapsulation)是将类中的某些部分(某些属性或者方法)隐藏起来,对象不能直接使用隐藏起来的属性或者方法,具有保护功能。
总结:隐藏对象的属性和方法实现细节,仅对外提供公共访问方式。
封装格式?
封装格式: __属性或者方法名称。(我们也叫做私有属性或者方法)
封装的目的?
封装的目的:保护隐私
比如你的银行卡号跟密码都必须设成私有属性,因为这是隐私。
私有属性
私有属性定义的格式:
__属性名=值
私有属性有什么特性?
在类的外部不能使用(对象不能调用私有属性)
代码示例:
在类中定义私有属性并在类的外面访问私有属性:
class Student:
def __init__(self,pet_name,account,password):
self.pet_name=pet_name
self.__account=account
self.__password=password
student=Student("小飞","xxxxxx","123456")
print(student.pet_name)
print(student.account)
print(student.password)
'''
运行结果:
小飞
AttributeError: 'Student' object has no attribute '__account'
AttributeError: 'Student' object has no attribute '__password'
'''
结论:私有属性访问失败了,那要如何访问私有属性呢?
在类中访问私有属性代码示例:
class Student:
def __init__(self,pet_name,account,password):
self.pet_name=pet_name
self.__account=account
self.__password=password
def print(self):
return "昵称:{},账号:{},密码:{}".format(self.pet_name,self.__account,self.__password)
student=Student("小飞","xxxxxx","123456")
student.print()
'''
运行结果:
昵称:小飞,账号:xxxxxx,密码:123456
'''
结论:不能在类的外面访问类的私有属性,这正是封装的意义。
私有方法
定义私有方法定义格式:
__方法名()
私有方法的作用?
就是在开发过程保护核心代码
定义私有方法,并在类的外面访问私有方法与普通方法、
代码示例:
class A:
def test(self):
print("test")
def __test1(self):
print("test1")
a=A()
a.test()
a.__test1()
'''
运行结果:
test
AttributeError: 'A' object has no attribute '__test1'
'''
结论:在类的外面访问类中私有方法失败了,那需要怎么访问类中的私有方法
class A:
def test(self):
print("test")
def __test1(self):
print("test1")
def print(self):
self.test()
self.__test1()
a = A()
a.print()
'''
运行结果:
test
test1
'''
结论:不能在类的外面访问类中的私有方法,这正是封装的意义。
注意事项:
1.在python中实现的封装操作,不是通过权限限制而是通过改名(name mangling 改名策略)实现的,名字变了找不到而已。
2.可以使用 dict可以查看属性(包括私有属性)的值 在类的内部使用私有属性,python内部会自动进行转换成 _类名__属性名。 在类的外部不能给对象添加私有属性因为不能转换成_类名__属性名类型。
3.可以通过 对象名.类名__方法或类名.类名__方法名访问到(但禁止这么干) 可以使用 _类名__私有属性名来获取值。但是一般情况下不要使用,了解即可