封装数据的主要缘由是:保护隐私python
封装方法的主要缘由是:隔离复杂度(快门就是傻瓜相机为傻瓜们提供的方法,该方法将内部复杂的照相功能都隐藏起来了,只提供了一个快门键,就能够直接拍照)编程
提示:在编程语言里,对外提供的接口(接口可理解为了一个入口),就是函数,称为接口函数,这与接口的概念还不同,接口表明一组接口函数的集合体。安全
在类里面封装其实就是:闭包
隐藏属性:是为了数据的安全编程语言
class Person: def __init__(self,name,age): self.__name=name self.age=age
p=Person('xichen',18) print(p.age)# 这个时候咱们实例化出来的对象是访问不到类init里的__name属性的,
如何访问被隐藏的属性函数
class Person: def __init__(self,name,age): self.__name=name self.age=age def get_name(self): # print(self.__name) return '[----%s-----]'%self.__name p=Person('xichen',18) print(p.age)
p=Person('xichen',18) print(p.get_name())
[----nick-----]code
print(p._Person__name)
[----nick-----]对象
3.隐藏方法:为了隔离复杂度继承
在继承中,父类若是不想让子类覆盖本身的方法,能够将方法定义为私有的接口
这里的隐藏的方法不想咱们的隐藏的属性同样能够有方法去用,隐藏的方法是用不了的
class Person: def __init__(self,name,age): self.__name=name self.__age=age def __speak(self): print('6666')
它能够把方法包装成数据属性
class Person: def __init__(self,name,height,weight): self.name=name self.height=height self.weight=weight @property # 使用语法糖的方式 经过property装饰器进行装饰 def bmi(self): return self.weight/(self.height**2) p=Person('xc',1.82,75) print(p.bmi) # 使用查看对象属性的方式 查看方法的返回值 # print(p.bmi()) # 错误的使用方法 # p.bmi = 123 # 只能查看,不能进行修改
22.6421929718633
使用property装饰器将方法包装成数据属性后,是没法进行修改的
class Person: def __init__(self,name,height,weight): self.__name=name self.__height=height self.__weight=weight @property def name(self): return '[个人名字是:%s]'%self.__name #用property装饰的方法名.setter,这样就能够修改了 @name.setter def name(self,new_name): # if not isinstance(new_name,str): if type(new_name) is not str: raise Exception('改不了') if new_name.startswith('sb'): raise Exception('不能以sb开头') self.__name=new_name p=Person('xc',1.82,70) # 按照属性进行调用 print(p.name) # 调用property装饰器后的方法 name,变为一个属性 # 按照属性进行调用,并修改 p.name='pppp' # 调用property.setter装饰器后的方法,能够进行修改 # 改不了,直接抛异常 # p.name=999 # p.name='sb_xxx'
通常没有这个需求。
class Person: def __init__(self, name, height, weight): self.__name = name self.__height = height self.__weight = weight @property def name(self): return '[个人名字是:%s]' % self.__name # 用property装饰的方法名.setter,这样就能够修改了 @name.setter def name(self, new_name): # if not isinstance(new_name,str): if type(new_name) is not str: raise Exception('改不了') if new_name.startswith('sb'): raise Exception('不能以sb开头') self.__name = new_name p = Person('xc', 1.82, 70) # 按照属性进行调用 print(p.name) # 调用property装饰器后的方法 name,变为一个属性 # 按照属性进行调用,并修改 p.name = 'pppp' # 调用property.setter装饰器后的方法,能够进行修改 # 改不了,直接抛一异常 # p.name=999 # p.name='sb_xxx' # 删除name,会调用property.deleter装饰的方法 del p.name