一、封装:

补充封装:

封装:

体现在两点:1、数据的封装(将数据封装到对象中)

obj= Foo('宝宝',22)2、封装方法和属性,将一类操作封装到一个类中classFoo:def __init__(self,name,age):

self.name=name

self.age=agedefshow (self):print(self.name,self.age)

什么是封装呢?(封装不是单纯意义的隐藏,其实它还是可以查看的)

就是把一些不想让别人看的给隐藏起来了

封装数据:目的是保护隐私

功能封装:目的是隔离复杂度

如果用了私有的,在类的外部,无法直接使用变形的属性,但是在类的内部可以直接使用

1 1.用我们常用的__init__方法里的self取值2 class Course:#恰好给我们提供了实现这种思路的方法

3 ##一种思路,python

4 def __init__(self,price,period,name):5 self.price =price6 self.period =period7 self.name =name8 c = Course(2000,'linux','6 months')9 print(c.period)10

11 2.在类里面定义一个空字典,然后装在字典里面取值12 defcourse(price,name ,period):13 dic ={}14 dic['price'] =price15 dic ['name'] =name16 dic ['period'] =period17 returndic18

19 c = Course(2000,'python','6 months')20 print(c.period) #对象名.属性名 查看属性的值

21

22 3.利用namedtuple方法23 from collections import namedtuple #只有属性没有方法的类

24 Course = namedtuple('Course',['name','price','period']) #传两个参数,第一个为自定义的名字,第二个传进去的是属性

25 python = Course('python',10000,'6 moths') #相当于实例化了

26 print(python.name)

对象名.属性名取值的三种方法

2.封装类属性的私有属性(就是类属性前面加__)

1 classGoods:2 #按照打八折计算 (定义了一个私有类属性)

3 __discount = 0.8 #变形后:_Goods__discount

4 def __init__(self,name,price):5 self.name =name6 self.price =price7 defgoods_price(self):8 return self.price * Goods.__discount

9 apple = Goods('apple',10)10 print(apple.goods_price())11 #print(Goods.__dict__) #类名.__dict__

12 print(Goods._Goods__discount)

类属性1

1 #封装:把你不想让人看的隐藏起来

2 #数据封装:目的保护隐私

3 classTeacher:4 __School = 'oldboy' #类属性

5 def __init__(self,name,salary):6 self.name =name7 self .__salary = salary #_Teacher__salary

8 #老师的属性 值

9 #怎么把薪水隐藏起来?

10 self.__salary=salary11 deffoo(self):12 print('------')13

14 t=Teacher('egon',2000)15 print(t.__dict__)16 #print(t.name)

17 print(t._Teacher__salary)#让显示出来

18 print(Teacher._Teacher__School) #类属性使用_类名__属性名

19 t.foo()20 #在本类内是可以正常调用的

21 #在本类外就必须以_类名__属性名调用(但是不建议你调)

类属性的私有方法

3.封装类对象的私有属性

成人的BMI数值:

过轻:低于18.5

正常:18.5-23.9

过重:24-27

肥胖:28-32

非常肥胖, 高于32

体质指数(BMI)=体重(kg)÷身高^2(m)

EX:70kg÷(1.75×1.75)=22.86

如上面的指标来计算下你自己的体质指数

1 classPerson:2 def __init__(self,height,weight,name,sex):3 self.__height = height #私有属性(让你不再外面调它)

4 #在本类中可以调用,在类外就不可以调用了

5 self.__weigth =weight6 self.__name =name7 self.__sex =sex8 def tell_bmi(self): #体重指数

9 return self.__weigth/self.__height ** 2 #在本类中可以调用

10

11 deftell_height(self):12 print(self.__height)13 def tell_weight(self): #告诉体重

14 return self.__weigth

15 def set_weigth(self,new_weight): #修改体重

16 if new_weight >20:17 self.__weigth =new_weight18 else:19 raise TypeError('你也太瘦了,瘦的连斤数都(快)没了') #如果体重小于20或者负的,就主动提示一个报错

20 egg = Person(1.6,96,'haiyan','female')21 print(egg.tell_bmi())22 #egg.__height #在类外不能调用

23 #print(egg._Person__height) #在类外查看得这样调用

24 print(egg.__dict__) #查看变形后的类型

25 #egg.set_weigth(-10)

26 #print(egg.tell_weigth())

27 egg.set_weigth(66) #修改体重为66

28 print(egg.tell_weight())

计算体质指数,衡量人健康的标准(对象的私有属性一)

1 classPeople:2 def __init__(self,name,age,sex,height):3 self.__name =name4 self.__age =age5 self.__sex =sex6 self.__height =height7

8 def tell_name(self): #看人名字

9 print(self.name)10 def set_name(self,val): #修改名字

11 if notisinstance(val, str):12 raise TypeError('名字必须是字符串类型')13 self.__name =val14 deftell_info(self):15 print('''

16 ---------%s info-----------17 name:%s18 age:%s19 sex:%s20 height:%s'''%(self.__name,self.__name,self.__age,self.__sex,self.__height))21

22 p=People('egon',21,'male','180')23 p.tell_info()24 p.set_name('haiyan') #调用修改名字的方法

25 p.tell_info()26 #print(p._People__name)#就可以看到了

对象属性的私有属性二

4.封装类方法的私有属性

1 #方法的私有属性

2 classParent:3 def __init__(self):4 self.__func() #__func==_Parent__func

5 def __func(self):6 print('Parent func')7

8 classSon(Parent):9 def __init__(self):10 self.__func() #_Son__func

11 def __func(self):12 print('Son func')13

14 def_Parent__func(self):15 print('son _Parent__func')16 s =Son()17 print(Parent.__dict__) #类名.__dict__查看变形后的结果

18

19 #私有属性:在本类内是可以正常调用的

20 #在本类外就必须以_类名__属性名调用(但是不建议你调)

类方法的私有属性1

1 classFoo:2 def __func(self):3 print('from foo')4 classBar(Foo):5 def __func(self):6 print('from bar')7 b =Bar()8 b._Foo__func()9 b._Bar__func()

方法的私有属性2

1 classFoo:2 def __init__(self,height,weight):3 self.height =height4 self.weight =weight5 def __heightpow(self): #私有方法

6 return self.height *self.height7 deftell_bmi(self):8 return self.weight/self.__heightpow()9

10 egon = Foo(1.7,120)11 print(egon.tell_bmi())12 print(Foo.__dict__)13 print(egon._Foo__heightpow()) #虽说是私有的,但是还是可以查看的

装饰方法的私有属性3

5.property

为什么要用property:将一个类的函数定义成特性以后,对象再去使用的时候obj.name,根本无法察觉自己的name是执行了一个函数然后计算出来的,这种特性的使用方式遵循了统一访问的原则

1.计算圆的面积和周长

1 from math importpi2 classCircle:3 def __init__(self,radius):4 self.radius =radius5 @property #装饰器:把一个方法当成一个属性用了

6 defarea(self):7 return self.radius * self.radius*pi8 @property9 defpeimeter(self):10 return 2*pi*self.radius11

12 c = Circle(10)13 print(c.area) #当成一个属性来调了,就不用加括号了

14 print(c.peimeter)

property

2.缓存网页信息

1 from urllib.request importurlopen2 classWeb_page:3 def __init__(self,url):4 self.url =url5 self.__content = None #内容设置为None

6 @property7 defcontent(self):8 if self.__content: #如果不为空,就说明已经下载了 _Web_page__content

9 return self.__content

10 else:11 self.__content = urlopen(self.url).read()#做缓存

12 return self.__content

13 mypage = Web_page('http://www.baidu.com')14 print(mypage.content)15 print(mypage.content)16 print(mypage.content)

property(2)

3.求和,平均值,最大值,最小值

1 classNum:2 def __init__(self,*args):3 print(args)4 if len(args)==1 and (type(args[0]) is list or type(args[0]) istuple):5 self.numbers=args[0]6 else:7 self.numbers =args8

9 @property10 defsum(self):11 returnsum(self.numbers)12

13 @property14 defavg(self):15 return self.sum/len(self.numbers)16

17 @property18 defmin(self):19 returnmin(self.numbers)20

21 @property22 defmax(self):23 returnmax(self.numbers)24 num = Num([3,1,3])25 vvv = Num(8,2,3)26 print(num.sum)27 print(num.min)28 print(num.avg)29 print(num.max)30 print('-----------')31 print(vvv.sum)32 print(vvv.min)33 print(vvv.avg)34 print(vvv.max)

property(3)

6.setter

1 classGoods:2 __discount = 0.8 #类的私有属性

3 def __init__(self,name,price):4 self.name =name5 self.__price =price6

7 @property8 defprice(self):9 #if hasattr(self,'__price'):

10 return self.__price * Goods.__discount

11 #else:

12 #raise NameError

13

14 @price.setter15 defprice(self,new_price):16 if type(new_price) isint:17 self.__price =new_price18

19 @price.deleter20 defprice(self):21 del self.__price

22

23 apple = Goods('apple',10)24 #print(apple.price)

25 apple.price = 20

26 print(apple.price)27

28 #del apple.price

29 #print(apple.price)

30 #apple.set_price(20)

31 #apple._Goods__apple

买东西

@property把一个类中的方法 伪装成属性

原来是obj.func()

现在是obj.func -->属性

1.因为属性不能被修改

所以用了@funcname.setter

obj.func = new_value 调用的是被@funcname.setter装饰器装饰的方法

被@property装饰的方法名必须和被@funcname.setter装饰的方法同名

2.也可以另一种方法修改,但是上一种方法吧一个类中的方法伪装成属性来调用了,而这种方法

还是原来实例化一样调用

例如:

1 classPeople:2 def __init__(self,name,age,sex,height):3 self.__name =name4 self.__age =age5 self.__sex =sex6 self.__height =height7

8 def tell_name(self): #看人名字

9 print(self.name)10 def set_name(self,val): #修改名字

11 if notisinstance(val, str):12 raise TypeError('名字必须是字符串类型')13 self.__name =val14 deftell_info(self):15 print('''

16 ---------%s info-----------17 name:%s18 age:%s19 sex:%s20 height:%s'''%(self.__name,self.__name,self.__age,self.__sex,self.__height))21

22 p=People('egon',21,'male','180')23 p.tell_info()24 p.set_name('haiyan') #调用修改名字的方法

25 p.tell_info()26 #print(p._People__name)#就可以看到了

View Code

python封装方法有几种_python之--------封装相关推荐

  1. python封装方法有几种_python之封装

    一.什么是封装 在程序设计中,封装(Encapsulation)是对具体对象的一种抽象,即将某些部分隐藏起来,在程序外部看不到,其含义是其他程序无法调用. 要了解封装,离不开"私有化&quo ...

  2. python封装方法有几种_Python中的封装有什么作用?

    展开全部 日常生活中可2113以看到很多的汽车5261,汽车包括车轮.发动机.车架等零4102部件.可以在车架1653上安装车轮,然后安装发动机,最后安装其他零件,刷漆.就形成了汽车.这个过程,是把各 ...

  3. python封装方法有几种_Python打包exe文件方法汇总【4种】

    Python 打包 exe 文件方法汇总 Python 作为解释型语言,发布即公开源码, 虽然是提倡开源但是有些时候就是忍不住想打包成 exe ,不仅仅是为了对代码进 行加密,而是为了跨平台.防止有些 ...

  4. [转载] python函数分为哪几种_python常用函数

    参考链接: Python中的等分算法函数bisect Python常用函数 python中函数以两种形式呈现:一是可以自己定义的函数function,比如最常用的print()函数:另外一种是作为类的 ...

  5. python函数分为哪几种_python常用函数

    Python常用函数 python中函数以两种形式呈现:一是可以自己定义的函数function,比如最常用的print()函数:另外一种是作为类的方法method调用,比如turtle.shapesi ...

  6. python的sort方法是哪种_python中的sort方法使用详解

    Python中的sort()方法用于数组排序,本文以实例形式对此加以详细说明: 一.基本形式列表有自己的sort方法,其对列表进行原址排序,既然是原址排序,那显然元组不可能拥有这种方法,因为元组是不可 ...

  7. python网络爬虫的方法有几种_Python网络爬虫过程中5种网页去重方法简要介绍

    一般的,我们想抓取一个网站所有的URL,首先通过起始URL,之后通过网络爬虫提取出该网页中所有的URL链接,之后再对提取出来的每个URL进行爬取,提取出各个网页中的新一轮URL,以此类推.整体的感觉就 ...

  8. python导入模块有几种_Python中几种导入模块的方式总结

    模块内部封装了很多实用的功能,有时在模块外部调用就需要将其导入.常见的方式有如下几种: 1 . import >>> import sys >>> sys.path ...

  9. python open方法下file模块_python 文件操作

    一.基本概述 基本的文件操作也就常见的几种,创建.打开.读取.写入和关闭文件等.Python中有几个内置模块和方法来处理文件.这些方法在例如os,os.path,shutil和pathlib等等几个模 ...

最新文章

  1. python中的数据写入与添加数据写入文件(to_csv)
  2. Spring框架学习day_01: 框架配置方式/ 管理对象的作用域/ 生命周期/ 组件扫描/ 单例模式:“懒汉式“,“饿汉式“
  3. 北京点击科技有限公司董事长兼总裁——王志东经典语录4
  4. python三层装饰器-python中自带的三个装饰器的实现
  5. js事件技巧方法整合
  6. 数据中心制冷基本原则及节能方案
  7. QT的QDesignerCustomWidgetInterface类的使用
  8. java中的==、equals()、hashCode()源码分析
  9. Oracle CPU使用率过高问题处理
  10. 【渝粤教育】国家开放大学2018年春季 0341-22T高级英语听力(2) 参考试题
  11. (47)FPGA同步复位与异步复位(异步复位同步释放)
  12. eclipse java 注释_Eclipse Java注释模板设置详解
  13. 游戏里的---Change
  14. 蓝桥杯 ALGO-101 算法训练 图形显示
  15. UML建模之时序图(Sequence Diagram)转
  16. 从yield关键字看IEnumerable和Collection的区别
  17. java毕业设计题目大全
  18. Java自定义动态数组
  19. 光学中的几个物理量的意义
  20. 事后诸葛亮分析(小小大佬带飞队)

热门文章

  1. php分享十五:php的数据库操作
  2. IE6/IE7下:inline-block不兼容的问题
  3. class a_class;与new class();的区别
  4. SAP HANA能否推动实时应用?
  5. 实现IHttpModule接口获取Session来实现页面访问日志功能。
  6. MySQL 全局锁和表锁
  7. 64 位来临:微软 Visual Studio 2022 预览版今夏发布,更多功能一览
  8. 阿里云学生计划领取攻略
  9. matlab2010alinux下载,Linux matlab 2010a 下载与安装过程
  10. c语言二级考试程序设计题难吗,计算机二级考试:题库抽的不是题是“命”!附赠考试通关全攻略!...