日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python封装方法有几种_python之--------封装

發(fā)布時間:2025/4/16 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python封装方法有几种_python之--------封装 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一、封裝:

補(bǔ)充封裝:

封裝:

體現(xiàn)在兩點(diǎn):1、數(shù)據(jù)的封裝(將數(shù)據(jù)封裝到對象中)

obj= Foo('寶寶',22)2、封裝方法和屬性,將一類操作封裝到一個類中classFoo:def __init__(self,name,age):

self.name=name

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

什么是封裝呢?(封裝不是單純意義的隱藏,其實(shí)它還是可以查看的)

就是把一些不想讓別人看的給隱藏起來了

封裝數(shù)據(jù):目的是保護(hù)隱私

功能封裝:目的是隔離復(fù)雜度

如果用了私有的,在類的外部,無法直接使用變形的屬性,但是在類的內(nèi)部可以直接使用

1 1.用我們常用的__init__方法里的self取值2 class Course:#恰好給我們提供了實(shí)現(xiàn)這種思路的方法

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']) #傳兩個參數(shù),第一個為自定義的名字,第二個傳進(jìn)去的是屬性

25 python = Course('python',10000,'6 moths') #相當(dāng)于實(shí)例化了

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 #數(shù)據(jù)封裝:目的保護(hù)隱私

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 #在本類內(nèi)是可以正常調(diào)用的

21 #在本類外就必須以_類名__屬性名調(diào)用(但是不建議你調(diào))

類屬性的私有方法

3.封裝類對象的私有屬性

成人的BMI數(shù)值:

過輕:低于18.5

正常:18.5-23.9

過重:24-27

肥胖:28-32

非常肥胖, 高于32

體質(zhì)指數(shù)(BMI)=體重(kg)÷身高^2(m)

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

如上面的指標(biāo)來計算下你自己的體質(zhì)指數(shù)

1 classPerson:2 def __init__(self,height,weight,name,sex):3 self.__height = height #私有屬性(讓你不再外面調(diào)它)

4 #在本類中可以調(diào)用,在類外就不可以調(diào)用了

5 self.__weigth =weight6 self.__name =name7 self.__sex =sex8 def tell_bmi(self): #體重指數(shù)

9 return self.__weigth/self.__height ** 2 #在本類中可以調(diào)用

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('你也太瘦了,瘦的連斤數(shù)都(快)沒了') #如果體重小于20或者負(fù)的,就主動提示一個報錯

20 egg = Person(1.6,96,'haiyan','female')21 print(egg.tell_bmi())22 #egg.__height #在類外不能調(diào)用

23 #print(egg._Person__height) #在類外查看得這樣調(diào)用

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())

計算體質(zhì)指數(shù),衡量人健康的標(biāo)準(zhǔn)(對象的私有屬性一)

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') #調(diào)用修改名字的方法

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__查看變形后的結(jié)果

18

19 #私有屬性:在本類內(nèi)是可以正常調(diào)用的

20 #在本類外就必須以_類名__屬性名調(diào)用(但是不建議你調(diào))

類方法的私有屬性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:將一個類的函數(shù)定義成特性以后,對象再去使用的時候obj.name,根本無法察覺自己的name是執(zhí)行了一個函數(shù)然后計算出來的,這種特性的使用方式遵循了統(tǒng)一訪問的原則

1.計算圓的面積和周長

1 from math importpi2 classCircle:3 def __init__(self,radius):4 self.radius =radius5 @property #裝飾器:把一個方法當(dāng)成一個屬性用了

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) #當(dāng)成一個屬性來調(diào)了,就不用加括號了

14 print(c.peimeter)

property

2.緩存網(wǎng)頁信息

1 from urllib.request importurlopen2 classWeb_page:3 def __init__(self,url):4 self.url =url5 self.__content = None #內(nèi)容設(shè)置為None

6 @property7 defcontent(self):8 if self.__content: #如果不為空,就說明已經(jīng)下載了 _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()

現(xiàn)在是obj.func -->屬性

1.因?yàn)閷傩圆荒鼙恍薷?/p>

所以用了@funcname.setter

obj.func = new_value 調(diào)用的是被@funcname.setter裝飾器裝飾的方法

被@property裝飾的方法名必須和被@funcname.setter裝飾的方法同名

2.也可以另一種方法修改,但是上一種方法吧一個類中的方法偽裝成屬性來調(diào)用了,而這種方法

還是原來實(shí)例化一樣調(diào)用

例如:

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') #調(diào)用修改名字的方法

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

View Code

總結(jié)

以上是生活随笔為你收集整理的python封装方法有几种_python之--------封装的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。