类的封装(property)
封装
封装程序的主要原因:保护隐私;而封装方法的主要原因是:隔离复杂的执行过程
- property的特性
将一个类的函数定义成特性以后,对象再去使用的时候obj.name,根本无法察觉自己的name是执行了一个函数然后计算出来的,这种特性的使用方式遵循了统一访问的原则
import math
class circular:
def __init__(self,radius,):
self.radius=radius
@property #area=property(area)
def area(self):
#print("圆的面积是:%s"%(int(self.radius)**2*self.Pi))
res=int(self.radius)**2*math.pi
print(res)
return res
@property #circumference=property(circumference)
def circumference(self):
# print("圆的周长是:%s"%(self.Pi*2*int(self.radius)))
res1=math.pi*2*int(self.radius)
print(res1)
return res1
t=circular("3")
t.area
t.circumference
"D:\Program Files\python.exe" "E:/py_code/day 12/类的封装.py"
28.274333882308138
18.84955592153876
Process finished with exit code 0
这里需要知道的用户在执行obj.area或者obj.circumference不能被赋值的,因为实际上执行的过程我们是调用的是一个函数,这里只是被伪装成一个对象的属性。所以这里需要特别注意
- 隐藏--功能
其次也有另一种方式:
class people:
def __init__(self,name,age,sex,height,weight):
self.__name=name #self.__name=_people__name
self.__age=age
self.__sex=sex
self.__height=height
self.__weight=weight
def tell_name(self):
print(self._name)
def set_name(self,val):
if not isinstance(val,str):
raise TypeError("名字必须是字符串类型")
self.__name=val
def tell_info(self):
print('''
------------%s info----------
name:%s
age:%s
sex:%s
height:%s
weight:%s
----------- info------------
''' %(self.__name,
self.__name,
self.__age,
self.__sex,
self.__height,
self.__weight))
t1=people("whatmini",18,"man","64kg","1.75")
t1.tell_info()
print(t1._people__age)
"D:\Program Files\python.exe" "E:/py_code/day 12/类.py"
------------whatmini info----------
name:whatmini
age:18
sex:man
height:64kg
weight:1.75
----------- info------------
18
Process finished with exit code 0
上述中self.__name=name实际就是将name的结果封装起来,真实存放的位置在self._people中,但是我们如果想要去访问则需要obj._people__name才能找到真实信息。很明显我们需要给用户提供提供一个封装好的接口给到其访问所以如下:
class people:
def __init__(self,name,age,sex,height,weight):
self.__name=name #self.__name=_people__name
self.__age=age
self.__sex=sex
self.__height=height
self.__weight=weight
@property
def name(self):
return self.__name # 用户查询name时会直接将name返回
def set_name(self,val):
if not isinstance(val,str):
raise TypeError("名字必须是字符串类型")
self.__name=val
def tell_info(self):
print('''
------------%s info----------
name:%s
age:%s
sex:%s
height:%s
weight:%s
----------- info------------
''' %(self.__name,
self.__name,
self.__age,
self.__sex,
self.__height,
self.__weight))
t1=people("whatmini",18,"man","64kg","1.75")
print(t1.name)
"D:\Program Files\python.exe" "E:/py_code/day 12/类.py"
whatmini
Process finished with exit code 0
这里同样我们会遇到一个问题就是如何去修改对象的属性,用户在调用对象属性时有时会对属性进行修改和删除的操作,但是此时的属性是被封装后的一个函数,所以这里要用到下面的两个函数:
- obj.setter
class people:
def __init__(self,name,age,sex,height,weight):
self.__name=name #self.__name=_people__name
self.__age=age
self.__sex=sex
self.__height=height
self.__weight=weight
@property
def name(self):
return self.__name # 用户查询name时会直接将name返回
@name.setter
def name(self,val):
if not isinstance(val,str):
raise TypeError("%s must be str"%val) #设置报错机制当指定用户的输入类型
self.__name=val #当用户输入的类型合格后则将用户的修改的值进行重新赋值
def tell_info(self):
print('''
------------%s info----------
name:%s
age:%s
sex:%s
height:%s
weight:%s
----------- info------------
''' %(self.__name,
self.__name,
self.__age,
self.__sex,
self.__height,
self.__weight))
t1=people("whatmini",18,"man","64kg","1.75")
t1.name="shan"
print(t1.name)
"D:\Program Files\python.exe" "E:/py_code/day 12/类.py"
shan
Process finished with exit code 0
- obj.name
class people:
def __init__(self,name,age,sex,height,weight,tag=False):
self.__name=name #self.__name=_people__name
self.__age=age
self.__sex=sex
self.__height=height
self.__weight=weight
self.tag=tag #设定标志位,当tag=True
@property
def name(self):
return self.__name # 用户查询name时会直接将name返回
@name.setter
def name(self,val):
if not isinstance(val,str):
raise TypeError("%s must be str"%val) #设置报错机制当指定用户的输入类型
self.__name=val #当用户输入的类型合格后则将用户的修改的值进行重新赋值
@name.deleter
def name(self):
if not self.tag:
raise PermissionError("Cannot perform")
del self.__name
def tell_info(self):
print('''
------------%s info----------
name:%s
age:%s
sex:%s
height:%s
weight:%s
----------- info------------
''' %(self.__name,
self.__name,
self.__age,
self.__sex,
self.__height,
self.__weight))
t1=people("whatmini",18,"man","64kg","1.75",True)
t1.name="shan"
del t1.name
print(t1.name)
"D:\Program Files\python.exe" "E:/py_code/day 12/类.py"
Traceback (most recent call last):
File "E:/py_code/day 12/类.py", line 262, in <module>
print(t1.name)
File "E:/py_code/day 12/类.py", line 229, in name
return self.__name # 用户查询name时会直接将name返回
AttributeError: 'people' object has no attribute '_people__name'
Process finished with exit code 1
这里可以看到我们已经将name这个对象属性删掉了。所以查看时编译器会进行报错。
类的封装(property)的更多相关文章
- python 类的封装/property类型/和对象的绑定与非绑定方法
目录 类的封装 类的property特性 类与对象的绑定方法与非绑定方法 类的封装 封装: 就是打包,封起来,装起来,把你丢进袋子里,然后用绳子把袋子绑紧,你还能拿到袋子里的那个人吗? 1.隐藏属性和 ...
- Python类总结-封装(Property, setter, deleter)
Property #property #内置装饰器函数,只在面向对象中使用 from math import pi class Circle: def __init__(self,r ): self. ...
- 抽象类,接口类,封装,property,classmetod,statimethod
抽象类,接口类,封装,property,classmetod,statimethod(类方法,静态方法) 一丶抽象类和接口类 接口类(不崇尚用) 接口类:是规范子类的一个模板,只要接口类中定义的,就应 ...
- 类的封装,property特性,类与对象的绑定方法和非绑定方法,
类的封装 就是把数据或者方法封装起来 为什么要封装 封装数据的主要原因是:保护隐私 封装方法的主要原因是:隔离复杂度(快门就是傻瓜相机为傻瓜们提供的方法,该方法将内部复杂的照相功能都隐藏起来了,比如你 ...
- Django分页类的封装
Django分页类的封装 Django ORM 封装 之前有提到(Django分页的实现)会多次用到分页,将分页功能封装起来能极大提高效率. 其实不是很难,就是将之前实现的代码全都放到类中,将需要用 ...
- iOS开发--QQ音乐练习,旋转动画的实现,音乐工具类的封装,定时器的使用技巧,SliderBar的事件处理
一.旋转动画的实现 二.音乐工具类的封装 -- 返回所有歌曲,返回当前播放歌曲,设置当前播放歌曲,返回下一首歌曲,返回上一首歌曲方法的实现 头文件 .m文件 #import "ChaosMu ...
- Java—类的封装、继承与多态
一.类和对象 1.类 类是数据以及对数据的一组操作的封装体. 类声明的格式: 类声明 { 成员变量的声明: 成员方法的声明及实现: } 1.1 声明类 [修饰符] class 类<泛型> ...
- 第三篇 :微信公众平台开发实战Java版之请求消息,响应消息以及事件消息类的封装
微信服务器和第三方服务器之间究竟是通过什么方式进行对话的? 下面,我们先看下图: 其实我们可以简单的理解: (1)首先,用户向微信服务器发送消息: (2)微信服务器接收到用户的消息处理之后,通过开发者 ...
- 025医疗项目-模块二:药品目录的导入导出-HSSF导入类的封装
上一篇文章提过,HSSF的用户模式会导致读取海量数据时很慢,所以我们采用的是事件驱动模式.这个模式类似于xml的sax解析.需要实现一个接口,HSSFListener接口. 原理:根据excel底层存 ...
随机推荐
- AIX盘rw_timeout值过小导致IO ERROR
刚下班没多久,接收到告警提示数据库的数据文件异常,且同时收到主机硬盘的IO ERROR告警 该数据库服务器为AIX+oracle 9i环境,登录主机验证关键日志告警 发现确实在18点48分有磁盘IO的 ...
- [python学习笔记] 运算符
数学运算符 与大多语言相同的运算符就不介绍了.不同的地方会用 (!不同)标出 与java相同的运算符 , - , * , % , / 不同之处 除法 (!不同) / 与java不同,整数相除,结果为 ...
- JS中基本的一些兼容问题 可能解释的不会太清楚
做兼容注意: 一如果两个都是属性,用逻辑||做兼容 二如果有一个是方法 用三目运算符做兼容 三多个属性或方法封装函数做兼容 一:谷歌浏览器和火狐浏览器鼠标滚动条兼容 1.document.docume ...
- String类的一些转换功能(6)
1:把字符串转换成字节数组 getBytes() 如: String s = "你好啊!" //编码 byte [] arr = s.getBytes();//这里默认编码格式是g ...
- grunt学习笔记1 理论知识
你需要检查js语法错误,然后再去压缩js代码.如果这两步你都去手动操作,会耗费很多成本.Grunt就能让你省去这些手动操作的成本. “—save-dev”的意思是,在当前目录安装grunt的同时,顺便 ...
- GCD之Apply
dispatch_apply函数是dispatch_sync函数和dispatch_group的结合体.该函数将按指定的次数将指定的block追加到指定的dispatch queue中,并等待全部处理 ...
- snsapi_base和snsapi_userinfo
1.以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的.用户感知的就是直接进入了回调页(往往是业务页面) 2.以snsap ...
- JS中var和let
前 言 JavaScript 大家都知道声明一个变量时,通常会用'var'来声明,但是在ES6中,定义了另一个关键字'let'.今天我就为大家带来'var'与'let'这两个关键字声明有何异同 ...
- swiper拖拽之后不自动滑动问题
//swiper轮播图 var mySwiper = new Swiper('.swiper-container',{ initialSlide :0, autoplay : 3000, direct ...
- PIC24 通过USB在线升级 -- USB HID bootloader
了解bootloader的实现,请加QQ: 1273623966 (验证填bootloader):欢迎咨询或定制bootloader; 我的博客主页www.cnblogs.com/geekygeek ...