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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python对象属性在引用时前面需要加()_python基础-面向对象进阶

發布時間:2023/12/10 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python对象属性在引用时前面需要加()_python基础-面向对象进阶 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

實現授權的關鍵點就是覆蓋__getattr__方法

1、通過觸發__getattr__方法,找到read方法

示例1:

1 importtime2 classFileHandle:3 def __init__(self,filename,mode='r',encoding='utf-8'):4 self.file=open(filename,mode,encoding=encoding)5 self.mode=mode6 self.encoding=encoding7

8 def __getattr__(self, item):9 print(item,type(item))10 self.file.read #self.file里面有read方法

11 return getattr(self.file,item) #能過字符串來找到,并通過return返回,就找到了read方法,

12

13 f1=FileHandle('a.txt','r')14 print(f1.file)15 print(f1.__dict__) #類的字典里,沒有read方法,就觸發了__getattr__方法

16 print(f1.read) #找到了read方法

17

18 sys_f=open('b.txt','w+')19 print('---->',getattr(sys_f,'read')) #找到了read方法

執行結果:

1 <_io.textiowrapper name="a.txt" mode="r" encoding="utf-8">

2

3 read

4

5

6

7 {'encoding': 'utf-8', 'file': <_io.textiowrapper name="a.txt" mode="r" encoding="utf-8">, 'mode': 'r'}8

9 ---->

View Code

2、往文件里面寫入內容

示例2:

1 importtime2 classFileHandle:3 def __init__(self,filename,mode='r',encoding='utf-8'):4 #self.filename=filename

5 self.file=open(filename,mode,encoding=encoding)6 self.mode=mode7 self.encoding=encoding8 defwrite(self,line):9 print('------------>',line)10 t=time.strftime('%Y-%m-%d %X')11 self.file.write('%s %s' %(t,line))12

13 def __getattr__(self, item):14 #print(item,type(item))

15 #self.file.read

16 returngetattr(self.file,item)17

18 f1=FileHandle('a.txt','w+')19 f1.write('1111111111111111\n')20 f1.write('cpu負載過高\n')21 f1.write('內存剩余不足\n')22 f1.write('硬盤剩余不足\n')

執行結果:

會創建一個a.txt的文件,并往里面寫入內容:

1 2016-12-23 18:34:16 1111111111111111

2 2016-12-23 18:34:16cpu負載過高3 2016-12-23 18:34:16內存剩余不足4 2016-12-23 18:34:16 硬盤剩余不足

七、isinstance(obj,cls)和issubclass(sub,super)

1、isinstance(obj,cls) 檢查是否obj是否是類cls的對象

示例:

1 classFoo(object):2 pass

3

4 obj =Foo()5

6 print(isinstance(obj,Foo))

執行結果:

1 True

2、issubclass(sub,super)檢查sub類是否是supper類的派生類

示例:

1 classFoo(object):2 pass

3

4 classBar(Foo):5 pass

6

7 print(issubclass(Bar,Foo))

執行結果:

1 True

八、__getattribute__

示例1:

不存在的屬性訪問,就會觸發__getattr__方法

1 classFoo:2 def __init__(self,x):3 self.x=x4

5 def __getattr__(self, item):6 print('執行的是我')7 #return self.__idct__[item]

8

9 f1=Foo(10)10 print(f1.x)11 f1.xxxxxx #不存在的屬性訪問,觸發__getattr__

執行結果:

1 10

2 執行的是我

示例2:

不管是否存在,都會執行__getattribute__方法

1 classFoo:2 def __init__(self,x):3 self.x=x4

5 def __getattribute__(self, item):6 print('不管是否存在,我都會執行')7

8 f1=Foo(10)9 f1.x10 f1.xxxxxxx

執行結果:

1 不管是否存在,我都會執行2 不管是否存在,我都會執行

示例:3:

1 classFoo:2 def __init__(self,x):3 self.x=x4

5 def __getattr__(self, item): #相當于監聽大哥的異常,大哥拋出導常,他就會接收。

6 print('執行的是我')7 #return self.__dict__[item]

8

9 def __getattribute__(self, item):10 print('不管是否存在,我都會執行')11 raise AttributeError('拋出異常了')12

13 f1=Foo(10)14 f1.x #結果是:10 ,調用會觸發系統的

15 f1.xxxxxxx #如果不存在會觸發自己定義的

執行結果:

1 不管是否存在,我都會執行2 執行的是我3 不管是否存在,我都會執行4 執行的是我

九、__setitem__,__getitem,__delitem__ ?(操作字典就用item的方式)

obj[‘屬性’]的方式去操作屬性時觸發的方法

__getitem__:obj['屬性'] 時觸發

__setitem__:obj['屬性']=屬性的值 時觸發

__delitem__:del obj['屬性'] 時觸發

示例1:

1 classFoo:2

3 def __getitem__(self, item):4 print('getitem',item)5 return self.__dict__[item]6

7 def __setitem__(self, key, value):8 print('setitem')9 self.__dict__[key]=value10

11 def __delitem__(self, key):12 print('delitem')13 self.__dict__.pop(key)14

15 f1=Foo()16 print(f1.__dict__)17 f1['name']='agon'

18 f1['age']=18

19 print('====>',f1.__dict__)20

21 del f1['name']22 print(f1.__dict__)23

24 print(f1,['age'])

執行結果:

1 {}2

3 setitem4

5 setitem6

7 ====> {'age': 18, 'name': 'agon'}8

9 delitem10

11 {'age': 18}12

13 <__main__.foo object at> ['age']

View Code

示例2:

1 classFoo:2 def __init__(self,name):3 self.name=name4

5 def __getitem__(self, item):6 print(self.__dict__[item])7

8 def __setitem__(self, key, value):9 self.__dict__[key]=value10 def __delitem__(self, key):11 print('del obj[key]時,我執行')12 self.__dict__.pop(key)13 def __delattr__(self, item):14 print('del obj.key時,我執行')15 self.__dict__.pop(item)16

17 f1=Foo('sb')18 f1['age']=18

19 f1['age1']=19

20 delf1.age121 del f1['age']22 f1['name']='alex'

23 print(f1.__dict__)

執行結果:

1 delobj.key時,我執行2

3 delobj[key]時,我執行4

5 {'name': 'alex'}

View Code

十、__str__, __repr__,__format__

1、改變對象的字符串顯示__str__,__repr__ ?(只能是字符串的值,不能是非字符串的值)

示例1:

1 l = list('hello')2 print(1)3

4 file=open('test.txt','w')5 print(file)

執行結果:

1 1

2 <_io.textiowrapper name="test.txt" mode="w" encoding="cp936">

View Code

示例2:

__str__方法

1 #自制str方法

2 classFoo:3 def __init__(self,name,age):4 self.name=name5 self.age=age6

7 def __str__(self):8 return '名字是%s 年齡是%s' %(self.name,self.age)9

10 f1=Foo('age',18)11 print(f1) #str(f1)---->f1.__str__()

12

13 x=str(f1)14 print(x)15

16 y=f1.__str__()17 print(y)

執行結果:

1 名字是age 年齡是182 名字是age 年齡是183 名字是age 年齡是18

View Code

示例3:

__repe__方法

1 #觸發__repr__方法,用在解釋器里輸出

2 classFoo:3 def __init__(self,name,age):4 self.name=name5 self.age=age6

7 def __repr__(self):8 return '名字是%s 年齡是%s' %(self.name,self.age)9

10 f1=Foo('agon',19)11 print(f1)

執行結果:

1 名字是agon 年齡是19

示例4:

__str__和__repe__ 共存時的用法

1 #當str與repr共存時

2 classFoo:3 def __init__(self,name,age):4 self.name=name5 self.age=age6

7 def __str__(self):8 return '名字是%s 年齡是%s' %(self.name,self.age)9

10 def __repr__(self):11 return '名字是%s 年齡是%s' %(self.name,self.age)12

13 f1=Foo('egon',19)14 #repr(f1)--->f1.__repr__()

15 print(f1) #str(f1)--->f1.__str__()---->f1.__repr__()

執行結果:

1 <__main__.foo object at>

View Code

總結:

str函數或者print函數--->obj.__str__()

repr或者交互式解釋器--->obj.__repr__()

如果__str__沒有被定義,那么就會使用__repr__來代替輸出

注意:這倆方法的返回值必須是字符串,否則拋出異常

2、自定制格式化字符串__format__

format的用法

示例1:

1 x = '{0}{0}{0}'.format('dog')2 print(x)

執行結果:

1 dogdogdog

不用__format__的方式實現

示例2:

1 classDate:2 def __init__(self,year,mon,day):3 self.year=year4 self.mon=mon5 self.day=day6

7 d1=Date(2016,12,26)8

9 x = '{0.year}{0.mon}{0.day}'.format(d1)10 y = '{0.year}:{0.mon}:{0.day}'.format(d1)11 z = '{0.year}-{0.mon}-{0.day}'.format(d1)12 print(x)13 print(y)14 print(z)

執行結果:

1 20161226

2 2016:12:26

3 2016-12-26

用__format__的方式實現

示例3:

1 format_dic={2 'ymd':'{0.year}:{0.month}:{0.day}',3 'm-d-y':'{0.month}-{0.day}-{0.year}',4 'y:m:d':'{0.year}:{0.month}:{0.day}',5 }6

7 classDate:8 def __init__(self,year,month,day):9 self.year=year10 self.month=month11 self.day=day12

13 def __format__(self, format_spec):14 print('我執行啦')15 print('----->',format_spec)16 if not format_spec or format_spec not informat_dic:17 format_spec='ymd'

18 fmt=format_dic[format_spec]19 returnfmt.format(self)20

21 d1=Date(2016,12,29)22 #print(format(d1)) #d1.__format__()

23 #print(format(d1))

24

25 print(format(d1,'ymd'))26 print(format(d1,'y:m:d'))27 print(format(d1,'m-d-y'))28 print(format(d1,'m-d:y'))29 print('===========>',format(d1,'sdsdddsfdsfdsfdsfdsfsdfdsfsdfds'))

執行結果:

1 我執行啦2 ----->ymd3 2016:12:29

4 我執行啦5 ----->y:m:d6 2016:12:29

7 我執行啦8 -----> m-d-y9 12-29-2016

10 我執行啦11 -----> m-d:y12 2016:12:29

13 我執行啦14 ----->sdsdddsfdsfdsfdsfdsfsdfdsfsdfds15 ===========> 2016:12:29

View Code

十一、?__slots__ ?(慎用)

1.__slots__是什么?是一個類變量,變量值可以是列表,元祖,或者可迭代對象,也可以是一個字符串(意味著所有實例只有一個數據屬性)

2.引子:使用點來訪問屬性本質就是在訪問類或者對象的__dict__屬性字典(類的字典是共享的,而每個實例的是獨立的)

3.為何使用__slots__:字典會占用大量內存,如果你有一個屬性很少的類,但是有很多實例,為了節省內存可以使用__slots__取代實例的__dict__ 當你定義__slots__后,__slots__就會為實例使用一種更加緊湊的內部表示。實例通過一個很小的固定大小的數組來構建,而不是為每個實例定義一個 字典,這跟元組或列表很類似。在__slots__中列出的屬性名在內部被映射到這個數組的指定小標上。使用__slots__一個不好的地方就是我們不能再給 實例添加新的屬性了,只能使用在__slots__中定義的那些屬性名。

4.注意事項:__slots__的很多特性都依賴于普通的基于字典的實現。另外,定義了__slots__后的類不再 支持一些普通類特性了,比如多繼承。大多數情況下,你應該 只在那些經常被使用到 的用作數據結構的類上定義__slots__比如在程序中需要創建某個類的幾百萬個實例對象 。 關于__slots__的一個常見誤區是它可以作為一個封裝工具來防止用戶給實例增加新的屬性。盡管使用__slots__可以達到這樣的目的,但是這個并不是它的初衷。更多的是用來作為一個內存優化工具。

__slots__的作用:節省內存空間

1、一個key的情況

示例1:

1 #__slots__ (作用:就是節省內存)

2 #一個key的值

3

4 classFoo:5 __slots__='name' #定義在類中的類變量,由這個類產生的實例,不在具有__dict__的屬性字典,限制了創建屬性

6

7 f1=Foo()8 f1.name='agon'

9 print(f1.name) #只能有一個name屬性

10 print(Foo.__slots__)11 print(f1.__slots__)

執行結果:

1 agon2 name3 name

View Code

2、兩個key的情況

示例2:

1 #兩個key的情況

2 classFoo:3 __slots__=['name','age']4

5 f1=Foo()6

7 print(Foo.__slots__)8 print(f1.__slots__)9 f1.name='egon'

10 f1.age=17

11 print(f1.name)12 print(f1.age)13 #f1.gender='male' #會報錯,加不上,#AttributeError: 'Foo' object has no attribute 'gender'

14

15 #只能定義__slots__提供的屬性(這里就定義了兩個屬性)大家都用一個屬性字典,優勢就是節省內存

16 f2=Foo()17 print(f2.__slots__)18 f2.name='alex'

19 f2.age=18

20 print(f2.name)21 print(f2.age)

執行結果:

1 ['name', 'age']2 ['name', 'age']3 egon4 17

5 ['name', 'age']6 alex7 18

十二、__doc__

1、它類的描述信息

示例:

1 classFoo:2 '我是描述信息'

3 pass

4

5 print(Foo.__doc__)

2、該屬性無法繼承

示例:

1 #__doc__ 該屬性無法繼承

2

3 classFoo:4 pass

5

6 classBar(Foo):7 pass

8

9 print(Foo.__dict__) #只要加上了__doc__,該屬性就無法繼承給子類

10 print(Bar.__dict__) #原理就是在底層字典里面,會加一個'__doc__': None,

十三、__module__和__class__

__module__ 表示當前操作的對象在那個模塊

__class__ ? ? 表示當前操作的對象的類是什么

1、創建lib/aa.py

1 #!/usr/bin/env python

2 #-*- coding:utf-8 -*-

3

4 classC:5

6 def __init__(self):7 self.name = ‘SB'8

9 lib/aa.py

2、輸出模塊和輸出類

1 from lib.aa importC2

3 obj =C()4 print obj.__module__ #輸出 lib.aa,即:輸出模塊

5 print obj.__class__ #輸出 lib.aa.C,即:輸出類

十四、__del__ 析構方法(垃圾回收時自動觸發)

析構方法,當對象在內存中被釋放時,自動觸發執行。

注:此方法一般無須定義,因為Python是一門高級語言,程序員在使用時無需關心內存的分配和釋放,因為此工作都是交給Python解釋器來執行,所以,析構函數的調用是由解釋器在進行垃圾回收時自動觸發執行的。

1 classFoo:2 def __init__(self,name):3 self.name=name4 def __del__(self):5 print('我執行啦')6

7 f1=Foo('alex')8

9 #del f1 #刪除實例會觸發__del__

10 del f1.name #刪除實例的屬性不會觸發__del__

11 print('---------------->')

執行結果:

1 ---------------->

2 我執行啦

十五、__call__

示例:

1 classFoo:2 def __call__(self, *args, **kwargs):3 print('實例執行啦 obj()')4

5 f1=Foo() #Foo下的__call__

6

7 f1() #abc下的__call__

執行結果:

1 實例執行啦 obj()

十六、?__next__和__iter__實現迭代器協議

一、什么是迭代器協議

1.迭代器協議是指:對象必須提供一個next方法,執行該方法要么返回迭代中的下一項,要么就引起一個StopIteration異常,以終止迭代 (只能往后走不能往前退)

2.可迭代對象:實現了迭代器協議的對象(如何實現:對象內部定義一個__iter__()方法)

3.協議是一種約定,可迭代對象實現了迭代器協議,python的內部工具(如for循環,sum,min,max函數等)使用迭代器協議訪問對象。

二、python中強大的for循環機制

for循環的本質:循環所有對象,全都是使用迭代器協議。

(字符串,列表,元組,字典,集合,文件對象)這些都不是可迭代對象,只不過在for循環式,調用了他們內部的__iter__方法,把他們變成了可迭代對象

然后for循環調用可迭代對象的__next__方法去取值,而且for循環會捕捉StopIteration異常,以終止迭代。

示例1:

1 #迭代器協議

2

3 classFoo:4 pass

5

6 l = list('hello')7 for i in l: #for循環本質就是調用他:f1.__iter__() == iter(f1)

8 print(i)

執行結果:

1 h2 e3 l4 l5 o

View Code

示例2:

1 classFoo:2 def __init__(self,n):3 self.n=n4

5 def __iter__(self): #把一個對象就成一個可迭代對象,必須有__iter__

6 returnself7

8 def __next__(self):9 self.n+=1

10 returnself.n11

12 f1=Foo(10)13 #for i in f1: #for循環本質就是調用他:f1.__iter__() == iter(f1)

14 #print(i)

15

16 print(f1.__next__())17 print(next(f1))18 print(next(f1))19 print(next(f1))20 print(next(f1))21 print(next(f1))22

23

24 for i in f1: #for循環本質就是調用他:f1.__iter__() == iter(f1)

25 print(i)

執行結果:

1 11

2 12

3 13

4 14

5 15

6 16

7 17

8 18

9 19

10 20

11 21

12 22

13 23

14 24

15 25

16 26

17 會一直無限循環下去.....18 下面部分省略.....

View Code

示例3:

1 classFoo:2 def __init__(self,n):3 self.n=n4

5 def __iter__(self): #把一個對象就成一個可迭代對象,必須有__iter__

6 returnself7

8 def __next__(self):9 if self.n == 13:10 raise StopIteration('終止了')11 self.n+=1

12 returnself.n13

14

15 f1=Foo(10)16

17 #print(f1.__next__())

18 #print(f1.__next__())

19 #print(f1.__next__())

20 #print(f1.__next__())

21

22 for i in f1: #f1.__iter__() == iter(f1)

23 print(i) #obj.__next__()

執行結果:

1 11

2 12

3 13

View Code

三、斐波那契數列

什么是斐波那契數列?

斐波那契數列指的是這樣一個數列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946........

這個數列從第3項開始,每一項都等于前兩項之和。

示例1:

1 1 2 (相當于1+1=2) #后面這個數是前兩個數之和

3 5 8 (相當于3+5=8) ? #后面這個數是前兩個數之和

用迭代器協議的方法實現:一次產生一個值

示例2:

1 #斐波那契數列

2 classFib:3 def __init__(self):4 self._a=1

5 self._b=1

6

7 def __iter__(self):8 returnself9 def __next__(self):10 if self._a > 100:11 raise StopIteration('終止了') # >100 就拋出異常12 self._a,self._b=self._b,self._a +self._b #1+1=b; a,b=b,a(等于交換值)13 returnself._a14

15 f1=Fib()16 print(next(f1))17 print(next(f1))18 print(next(f1))19 print(next(f1))20 print(next(f1))21 print('==================================')22 for i inf1:23 print(i)

執行結果:

1 1

2 2

3 3

4 5

5 8 #print(next(f1))

6 ==================================

7 13 #for循環的值

8 21

9 34

10 55

11 89

12 144

十七、描述符(__get__,__set__,__delete__) ?(新式類中描述符在大型開發中常用,必須掌握。)

描述符是什么:描述符本質就是一個新式類,在這個新式類中,至少實現了__get__(),__set__(),__delete__()三個方法中的一個,這也被稱為描述符協議。

1 class描述符:2 def __get__():3 pass

4 def __set__():5 pass

6 def __delete__():7 pass

8

9 class類:10 name=描述符()11

12 obj=類()13 obj.name #get方法

14 obj.name='egon' #set方法

15 del obj.name #delete

描述符的三種方法:

__get__(): ?.調用一個屬性時,觸發

__set__(): ? .為一個屬性賦值時,觸發

__delete__(): ?采用del.刪除屬性時,觸發

1、定義一個描述符

示例1:

1 class Foo: #在python3中Foo是新式類,它實現了三種方法,這個類就被稱作一個描述符

2 def __get__(self,instance,owner):3 print('get方法')4 def __set__(self, instance, value):5 print('set方法')6 def __delete__(self, instance):7 print('delete方法')

2、描述符是干什么的:描述符的作用是用來代理另外一個類的屬性的(必須把描述符定義成這個類的類屬性,不能定義到構造函數中)

示例2:

1 classFoo:2 def __get__(self,instance,owner):3 print('===>get方法')4 def __set__(self, instance, value):5 print('===>set方法')6 def __delete__(self, instance):7 print('===>delete方法')8

9 #包含這三個方法的新式類稱為描述符,由這個類產生的實例進行屬性的調用/賦值/刪除,并不會觸發這三個方法

10 f1=Foo()11 f1.name='egon'

12 print(f1.name)13 delf1.name14 #疑問:何時,何地,會觸發這三個方法的執行

3、描述符應用之何時?何地?

示例3:

1 #描述符應用之何時?何地?

2

3 #描述符Str

4 classFoo:5 def __get__(self,instance,owner):6 print('===>get方法')7 def __set__(self, instance, value):8 print('===>set方法')9 def __delete__(self, instance):10 print('===>delete方法')11

12

13 classBar:14 x=Foo() #在何地?

15

16 print(Bar.__dict__)17

18 #在何時?

19 b1=Bar()20 #b1.x #調用就會觸發上面的get方法

21 #b1.x=1 #賦值

22 #del b1.x

23 print(b1.x) #觸發了描述器里面的get方法,得到None

24 b1.x=1 #觸發了描述器里面的set方法,得到{}

25 print(b1.__dict__) #寫到b1的屬性字典中

26

27 del b1.x #打印===>delete方法

執行結果:

1 {'x': <__main__.foo object at>, '__weakref__': , '__dict__': , '__doc__': None, '__module__': '__main__'}2

3 ===>get方法4

5 None6

7 ===>set方法8

9 {}10

11 ===>delete方法

View Code

4、描述符分兩種

一、數據描述符:至少實現了__get__()和__set__()兩種方法

示例:

1 classFoo:2 def __set__(self, instance, value):3 print('set')4 def __get__(self, instance, owner):5 print('get')

二、非數據描述符:沒有實現__set__()方法

示例:

1 classFoo:2 def __get__(self, instance, owner):3 print('get')

5、注意事項:

一、描述符本身應該定義成新式類,被代理的類也應該是新式類

二、必須把描述符定義成另外一個類觸發的類屬性,不能為定義到構造函數中

示例:

1 classFoo:2 def __get__(self,instance,owner):3 print('===>get方法')4 def __set__(self, instance, value):5 print('===>set方法')6 def __delete__(self, instance):7 print('===>delete方法')8

9 classBar:10 x=Foo() #定義一個描述符

11 def __init__(self,n):12 self.x=n13

14 b1=Bar(10) #觸發set方法

15 print(b1.__dict__)

執行結果:

1 ===>set方法2 {}

三、要嚴格遵循該優先級,優先級由高到底分別是

1.類屬性

2.數據描述符

3.實例屬性

4.非數據描述符

5.找不到的屬性觸發__getattr__()

類屬性>數據描述符

示例:

1 classFoo:2 def __get__(self,instance,owner):3 print('===>get方法')4 def __set__(self, instance, value):5 print('===>set方法')6 def __delete__(self, instance):7 print('===>delete方法')8

9 classBar:10 x=Foo() #調用foo()屬性,會觸發get方法

11

12 print(Bar.x) #類屬性比描述符有更高的優先級,會觸發get方法

13 Bar.x=1 #自己定義了一個類屬性,并賦值給x,跟描述符沒有關系,所以他不會觸發描述符的方法

14 #print(Bar.__dict__)

15 print(Bar.x)

執行結果:

1 ===>get方法2 None3 1

數據描述符>實例屬性

示例1:

1 #有get,set就是數據描述符,數據描述符比實例屬性有更高的優化級

2

3 classFoo:4 def __get__(self,instance,owner):5 print('===>get方法')6 def __set__(self, instance, value):7 print('===>set方法')8 def __delete__(self, instance):9 print('===>delete方法')10

11 classBar:12 x = Foo() #調用foo()屬性,會觸發get方法

13

14 b1=Bar() #在自己的屬性字典里面找,找不到就去類里面找,會觸發__get__方法

15 b1.x #調用一個屬性的時候觸發get方法

16 b1.x=1 #為一個屬性賦值的時候觸發set方法

17 del b1.x #采用del刪除屬性時觸發delete方法

執行結果:

1 1 ===>get方法2 2 ===>set方法3 3 ===>delete方法

示例2:

1 classFoo:2 def __get__(self,instance,owner):3 print('===>get方法')4

5 def __set__(self, instance, value):6 pass

7

8 classBar:9 x =Foo()10

11 b1=Bar()12 b1.x=1 #觸發的是非數據描述符的set方法

13 print(b1.__dict__)

執行結果:

1 {} #數據描述符>實例屬性

類屬性>數據描述符>實例屬性

1 #類屬性>數據描述符>實例屬性

2

3 classFoo:4 def __get__(self,instance,owner):5 print('===>get方法')6 def __set__(self, instance, value):7 print('===>set方法')8 def __delete__(self, instance):9 print('===>delete方法')10

11 classBar:12 x = Foo() #調用foo()屬性,會觸發get方法

13

14 b1=Bar() #實例化

15 Bar.x=11111111111111111 #不會觸發get方法

16 b1.x #會觸發get方法

17

18 del Bar.x #已經給刪除,所以調用不了!報錯:AttributeError: 'Bar' object has no attribute 'x'

19 b1.x

非數據描述符

示例1:

1 #非數據描述符沒有set方法

2 classFoo:3 def __get__(self,instance,owner):4 print('===>get方法')5

6 def __delete__(self, instance):7 print('===>delete方法')8

9 classBar:10 x =Foo()11

12 b1=Bar()13 b1.x #自己類中沒有,就會去Foo類中找,所以就會觸發__get__方法

執行結果:

===>get方法

示例2:

1 #實例屬性>非數據描述符

2 classFoo:3 def __get__(self,instance,owner):4 print('===>get方法')5

6 classBar:7 x =Foo()8

9 b1=Bar()10 b1.x=1

11 print(b1.__dict__) #在自己的屬性字典里面,{'x': 1}

執行結果:

1 {'x': 1}

非數據描述符>找不到

1 #非數據描述符>找不到

2

3 classFoo:4 def __get__(self,instance,owner):5 print('===>get方法')6

7 classBar:8 x =Foo()9 def __getattr__(self, item):10 print('------------>')11

12 b1=Bar()13 b1.xxxxxxxxxxxxxxxxxxx #調用沒有的xxxxxxx,就會觸發__getattr__方法

執行結果:

1 ------------> #解發__getattr__方法

四、描述符應用

示例1:

1 classTyped: #有__get__,__set__,__delete__ 就是:數據描述符2 def __get__(self, instance,owner):3 print('get方法')4 print('instance參數【%s】' %instance)5 print('owner參數【%s】' %owner)6

7 def __set__(self, instance, value):8 print('set方法')9 print('instance參數【%s】' %instance)10 print('value參數【%s】' %value)11

12 def __delete__(self, instance):13 print('delete方法')14 print('instance參數【%s】'%instance)15

16

17 classPeople:18 name=Typed() #設置代理(代理的就是name屬性)19 def __init__(self,name,age,salary):20 self.name=name #觸發的是代理

21 self.age=age22 self.salary=salary23

24 p1=People('alex',13,13.3)25 #'alex' #觸發set方法

26 p1.name #觸發get方法,沒有返回值

27 p1.name='age' #觸發set方法

28 print(p1.__dict__) #{'salary': 13.3, 'age': 13}

執行結果:

1 set方法2 instance參數【<__main__.people object at>】3 value參數【alex】4 get方法5 instance參數【<__main__.people object at>】6 owner參數【】7 set方法8 instance參數【<__main__.people object at>】9 value參數【age】10 {'salary': 13.3, 'age': 13}

View Code

示例2:給字典屬性傳值

1 #給字典里面傳入值

2 classTyped:3 def __init__(self,key):4 self.key=key5

6 def __get__(self, instance, owner):7 print('get方法')8 return instance.__dict__[self.key] #觸發get方法,會返回字典的值

9

10 def __set__(self, instance, value):11 print('set方法')12 instance.__dict__[self.key]=value #存在p1的屬性字典里面

13

14 def __delete__(self, instance):15 print('delete方法')16 instance.__dict__.pop(self.key)17

18 classPeople:19 name=Typed('name') #name屬性被Typed給代理了,t1._set_() self._set__()

20 def __init__(self,name,age,salary):21 self.name=name22 self.age=age23 self.salary=salary24

25 p1=People('alex',13,13.3)26

27 #打印實例字典

28 print(p1.__dict__)29

30 #創建屬性,給name賦值,相當于修改了name字典的值

31 p1.name='egon' #觸發的是set方法

32 print(p1.__dict__)33

34 #刪除name屬性

35 print(p1.__dict__)36 del p1.name #觸發的是delete方法

37 print(p1.__dict__)

執行結果:

1 #打印實例屬性字典

2 set方法3 {'age': 13, 'salary': 13.3, 'name': 'alex'}4

5 #修改name字典的值

6 set方法7 {'age': 13, 'salary': 13.3, 'name': 'egon'}8

9 #刪除name屬性

10 delete方法11 {'age': 13, 'salary': 13.3}

示例3:

實現類型檢測的兩種方法:

方法一:用return的方式

1 #判斷他傳入的值是不是字符串類型

2 classTyped:3 def __init__(self,key):4 self.key=key5

6 def __get__(self, instance, owner):7 print('get方法')8 return instance.__dict__[self.key] #觸發get方法,會返回字典的值

9

10 def __set__(self, instance, value):11 print('set方法')12 if notisinstance(value,str):13 print('你傳入的類型不是字符串,錯誤')14 return #return的作用就是終止這個屬性字典,讓他的值設置不進字典中。

15 instance.__dict__[self.key]=value #存在p1的屬性字典里面

16

17 def __delete__(self, instance):18 print('delete方法')19 instance.__dict__.pop(self.key)20

21 classPeople:22 name=Typed('name') #name屬性被Typed給代理了,t1._set_() self._set__()

23 def __init__(self,name,age,salary):24 self.name=name25 self.age=age26 self.salary=salary27

28 #正常的情況下__dict__里面有沒有'name':'alex'

29 p1=People('alex',13,13.3)30 print(p1.__dict__) #觸發set方法,得到的值是{'salary': 13.3, 'name': 'alex', 'age': 13}

31

32 #不正常的情況下,修改'name':213 不等于字符串,改成了int類型

33 p1=People(213,13,13.3)34 print(p1.__dict__) #觸發set方法,得到的值是{'salary': 13.3, 'name': 'alex', 'age': 13}

執行結果:

1 set方法2 {'salary': 13.3, 'age': 13, 'name': 'alex'}3

4 set方法5 你傳入的類型不是字符串,錯誤6 {'salary': 13.3, 'age': 13}

方法二:用raise拋出異常的方式,判斷他傳入的值是不是字符串類型,(寫死了,不靈活)

1 #用拋出異常的方式,判斷他傳入的值是不是字符串類型

2 classTyped:3 def __init__(self,key):4 self.key=key5

6 def __get__(self, instance, owner):7 print('get方法')8 return instance.__dict__[self.key] #觸發get方法,會返回字典的值

9

10 def __set__(self, instance, value):11 print('set方法')12 if notisinstance(value,str): #判斷是否是字符串類型13 #方法一:return的方式

14 # print('你傳入的類型不是字符串,錯誤')

15 # return #return的作用就是終止這個屬性字典,讓他的值設置不進字典中。

16 #方法二:

17 raise TypeError('你傳入的類型不是字符串') ##用拋出異常的方式,判斷他傳入的值是不是字符串類型

18 instance.__dict__[self.key]=value #存在p1的屬性字典里面

19

20 def __delete__(self, instance):21 print('delete方法')22 instance.__dict__.pop(self.key)23

24 classPeople:25 name=Typed('name') #name屬性被Typed給代理了,t1._set_() self._set__()

26 def __init__(self,name,age,salary):27 self.name=name28 self.age=age29 self.salary=salary30

31 #正常的情況下__dict__里面有沒有'name':'alex'

32 #p1=People('alex',13,13.3)

33 #print(p1.__dict__) #觸發set方法,得到的值是{'salary': 13.3, 'name': 'alex', 'age': 13}

34

35 #不正常的情況下,修改'name':213 不等于字符串,改成了int類型

36 p1=People(213,13,13.3)37 print(p1.__dict__) #觸發set方法,得到的值是{'salary': 13.3, 'name': 'alex', 'age': 13}

執行結果:

1 Traceback (most recent call last):2 set方法3 File "D:/python/day28/5-1.py", line 219, in

4 {'name': 'alex', 'age': 13, 'salary': 13.3}5 set方法6 p1=People(213,13,13.3)7 File "D:/python/day28/5-1.py", line 210, in __init__

8 self.name=name9 File "D:/python/day28/5-1.py", line 200, in __set__

10 raise TypeError('你傳入的類型不是字符串')11 TypeError: 你傳入的類型不是字符串

類型檢測加強版

示例:4:用raise拋出異常的方式,判斷傳入的值是什么類型,同時可以判斷多個屬性(推薦寫法)

1 #用拋出異常的方式,判斷他傳入的值是什么類型 (不寫死的方式,判斷傳入值的類型)

2 classTyped:3 def __init__(self,key,expected_type):4 self.key=key5 self.expected_type=expected_type6

7 def __get__(self, instance, owner):8 print('get方法')9 return instance.__dict__[self.key] #觸發get方法,會返回字典的值

10

11 def __set__(self, instance, value):12 print('set方法')13 if notisinstance(value,self.expected_type):14 raise TypeError('%s 你傳入的類型不是%s' %(self.key,self.expected_type)) #用拋出異常的方式,判斷他傳入的值是什么類型,同時可以判斷多個屬性的類型

15 instance.__dict__[self.key]=value #存在p1的屬性字典里面

16

17 def __delete__(self, instance):18 print('delete方法')19 instance.__dict__.pop(self.key)20

21 classPeople:22 name=Typed('name',str) #name設置代理Typed

23 age=Typed('age',int) #age設置代理Typed

24 def __init__(self,name,age,salary):25 self.name=name #alex傳給代理,會觸發set方法

26 self.age=age #age傳給代理,會觸發set方法

27 self.salary=salary28

29 #name是字符串,age是整型,salary必須是浮點數

30 #正確的方式

31 p1=People('alex',13,13.3)32

33 #傳入錯誤的類型,會判斷傳入值的類型

34 #name要求傳入的srt,但這里傳入的是整型,所以會報錯,說你傳入的不是srt類型

35 p1=People(213,13,13.3)

執行結果:

1 set方法2 File "D:/python/day28/5-1.py", line 220, in

3 p1=People(213,13,13.3)4 set方法5 File "D:/python/day28/5-1.py", line 210, in __init__

6 set方法7 self.name=name8 File "D:/python/day28/5-1.py", line 199, in __set__

9 raise TypeError('%s 你傳入的類型不是%s' %(self.key,self.expected_type)) #用拋出異常的方式,判斷他傳入的值是什么類型

10

11 TypeError: name 你傳入的類型不是

View Code

十八、__enter__和__exit__

1、操作文件寫法

1 with open('a.txt') as f:2   '代碼塊'

2、上述叫做上下文管理協議,即with語句,為了讓一個對象兼容with語句,必須在這個對象的類中聲明__enter__和__exit__方法

1 classOpen:2 def __init__(self,name):3 self.name=name4

5 def __enter__(self):6 print('出現with語句,對象的__enter__被觸發,有返回值則賦值給as聲明的變量')7 #return self

8 def __exit__(self, exc_type, exc_val, exc_tb):9 print('with中代碼塊執行完畢時執行我啊')10

11

12 with Open('a.txt') as f: #with語句,觸發__enter__,返回值賦值給f13 print('=====>執行代碼塊')14 #print(f,f.name)

執行結果:

1 出現with語句,對象的__enter__被觸發,有返回值則賦值給as聲明的變量2 =====>執行代碼塊3 with中代碼塊執行完畢時執行我啊

3、執行代碼塊

__exit__()中的三個參數分別代表異常類型,異常值和追溯信息,with語句中代碼塊出現異常,則with后的代碼都無法執行

沒有異常的情況下,整個代碼塊運行完畢后去觸發__exit__,它的三個參數都會執行

1 classFoo:2 def __init__(self,name):3 self.name=name4

5 def __enter__(self):6 print('執行enter')

7 returnself #2、拿到的結果是self,并賦值給f8

9 def __exit__(self, exc_type, exc_val, exc_tb): #4、觸發__exit__,然后執行print()10 print('執行exit')11 print(exc_type)12 print(exc_val)13 print(exc_tb)14

15

16 with Foo('a.txt') as f: #1、with觸發的是__enter__,拿到的結果是self并賦值給f;17 print(f) #3、然后會執行with代碼塊,執行完畢后

18 print(assfsfdsfdsfdsfffsadfdsafdsafdsafdsafdsafdsafdsafdsad)

19 print(f.name)

20 print('000000000000000000000000000000000000000000000000000000')

執行結果:

1 執行enter2 Traceback (most recent call last):3 <__main__.foo object at>

4 File "D:/python/day28/s1.py", line 56, in

5 執行exit6 print(assfsfdsfdsfdsfffsadfdsafdsafdsafdsafdsafdsafdsafdsad) #觸發__exit__

7

8 NameError: name 'assfsfdsfdsfdsfffsadfdsafdsafdsafdsafdsafdsafdsafdsad' is notdefined9 name 'assfsfdsfdsfdsfffsadfdsafdsafdsafdsafdsafdsafdsafdsad' is notdefined10

View Code

4、有返回值

如果__exit()返回值為True,那么異常會被清空,就好像啥都沒發生一樣,with后的語句正常執行

1 classFoo:2 def __init__(self,name):3 self.name=name4

5 def __enter__(self):6 print('執行enter')

7 returnself8 '''class、異常值、追蹤信息'''

9 def __exit__(self, exc_type, exc_val, exc_tb): #2、有異常的時候,就會觸發__exit__方法10 print('執行exit')11 print(exc_type)12 print(exc_val)13 print(exc_tb)14 return True #3、沒有return True就會報錯,如果有return True異常自己吃了,不報異常

15

16 with Foo('a.txt') as f:17 print(f)

18 print(assfsfdsfdsfdsfffsadfdsafdsafdsafdsafdsafdsafdsafdsad) #1、有異常的情況,他就會觸發__exit__

19 print(f.name) #不執行這行,直接打印下面那行

20 print('000000000000000000000000000000000000000000000000000000') #4、最后打印這行

執行結果:

1 執行enter2 <__main__.foo object at>

3 執行exit4

5 name 'assfsfdsfdsfdsfffsadfdsafdsafdsafdsafdsafdsafdsafdsad' is notdefined6

7 000000000000000000000000000000000000000000000000000000

View Code

總結:

with obj as f:

'代碼塊'

1.with obj ---->觸發obj.__enter__(),拿到返回值

2.as f----->f=返回值、

3.with obj as f 等同于 f=obj.__enter__()

4.執行代碼塊

一:沒有異常的情況下,整個代碼塊運行完畢后去觸發__exit__,它的三個參數都為None

二:有異常的情況下,從異常出現的位置直接觸發__exit__

a:如果__exit__的返回值為True,代表吞掉了異常

b:如果__exit__的返回值不為True,代表吐出了異常

c:__exit__的的運行完畢就代表了整個with語句的執行完畢

用途:

1.使用with語句的目的就是把代碼塊放入with中執行,with結束后,自動完成清理工作,無須手動干預

2.在需要管理一些資源比如文件,網絡連接(TCP協議建連接、傳輸數據、關連接)和鎖(進程,線程)的編程環境中,可以在__exit__中定制自動釋放資源的機制,你無須再去關系這個問題,這將大有用處。

十九、類的裝飾器

示例1:類的裝飾器基本原理

1 #示例1

2 defdeco(func): #高階函數3 print('===================')4 return func #fuc=test

5

6 @deco #裝飾器test=deco(test)

7 deftest():8 print('test函數運行')9 test() #運行test

執行結果:

1 ===================

2 test函數運行

示例2:類的裝飾器基本原理

1 defdeco(obj):2 print('============',obj)3 obj.x=1 #增加屬性

4 obj.y=2

5 obj.z=3

6 returnobj7

8 @deco #Foo=deco(Foo) #@deco語法糖的基本原理(語法糖可以在函數前面加,也可以在類的前面加)

9 classFoo: #類的裝飾器10 pass

11

12 print(Foo.__dict__) #加到屬性字典中

執行結果:

1 ============

2 {'__module__': '__main__', 'z': 3, 'x': 1, '__dict__': , '__doc__': None, '__weakref__': , 'y': 2}

用法總結:@deco語法糖可以在函數前面加,也可以在類的前面加

示例3:一切皆對象

1 defdeco(obj):2 print('==========',obj)3 obj.x=1

4 obj.y=2

5 obj.z=3

6 returnobj7

8 #@deco #Foo=deco(test)

9 deftest():10 print('test函數')11 test.x=1 #但沒有人會這么做,只是驗證一切皆對象

12 test.y=1

13 print(test.__dict__)

執行結果:

1 {'x': 1, 'y': 1}

示例4:直接傳值并加到字典中

1 def Typed(**kwargs): #負責接收參數

2 def deco(obj): #局部作用域

3 obj.x=1

4 obj.y=2

5 obj.z=3

6 returnobj7 print('====>',kwargs) #外層傳了個字典進來,就是: 'y': 2, 'x': 1,

8 returndeco9

10 @Typed(x=1,y=2,z=3) #typed(x=1,y=2,z=3)--->deco 函數名加()就是運行Typed函數

11 classFoo:12 pass

執行結果:

1 ====> {'y': 2, 'x': 1, 'z': 3}

示例5:類的裝飾器增強版

1 def Typed(**kwargs): #Type傳過來的參數,就是name='egon',kwargs包含的就是一個字典2 defdeco(obj):3 for key,val inkwargs.items(): #key=name,val=age4 setattr(obj,key,val) #obj=類名,key=name,val=age5 returnobj #返回類本身:obj,就相當于給類加了個屬性6 returndeco7

8 @Typed(x=1,y=2,z=3) #1、typed(x=1,y=2,z=3)--->deco 2、@deco--->Foo=deco(Foo)

9 classFoo:10 pass

11 print(Foo.__dict__)12

13 @Typed(name='egon') #@deco---->Bar=deco(Bar),重新賦值給了Bar14 classBar:15 pass

16 print(Bar.name) #最后打印name,就得到egon

執行結果:

1 {'y': 2, '__dict__': , 'z': 3, '__weakref__': , '__module__': '__main__','x': 1, '__doc__': None}2

3 egon

實現:類型檢測控制傳入的值是什么類型

1、用raise拋出異常的方式實現

2、用類加裝飾器實現 (這種方法更高級)

示例6:類加裝飾器的應用

示例如下:

1、給類加裝飾器,實現控制傳入的類型(推薦寫法) ?可以參考: ?示例:4:用raise拋出異常的方式,判斷傳入的值是什么類型,同時可以判斷多個屬性。

1 #給類加裝飾器,實現控制傳入的類型

2

3 classTyped:4 def __init__(self,key,expected_type):5 self.key=key6 self.expected_type=expected_type7

8 def __get__(self, instance, owner):9 print('get方法')10 return instance.__dict__[self.key]11

12 def __set__(self, instance, value):13 print('set方法')14 if notisinstance(value,self.expected_type):15 raise TypeError('%s 傳入的類型不是%s' %(self.key,self.expected_type))16 instance.__dict__[self.key]=value17

18 def __delete__(self, instance):19 print('delete方法')20 instance.__dict__.pop(self.key)21

22 def deco(**kwargs): #kwargs={'name':str,'age':int}

23 def wrapper(obj): #obj=People

24 for key,val in kwargs.items(): #(('name',str),('age',int))

25 #print(obj,key)

26 setattr(obj,key,Typed(key,val)) #給People設置類屬性

27 returnobj28 returnwrapper29

30 #給類加裝飾器,加了裝飾器,指定了什么類型,就必須傳入什么類型的值,否則就會報錯

31 @deco(name=str,age=int,salary=float) #@wrapper ===>People=wrapper(People) #實現這個功能的重點在這里

32 classPeople:33 #name=Typed('name',int)

34 def __init__(self,name,age,salary):35 self.name=name36 self.age=age37 self.salary=salary38

39 #name=srt,age=int,salary=float

40#傳入的是正確的類型,所以不會報錯。

41 p1 = People('alex', 13, 13.3)42 print(People.__dict__)43

44 #age設置成了int型,我們傳入的是字符串類型,所以會報錯:TypeError: age 傳入的類型不是

45 #p1=People('alex','13',13.3)

46 #print(People.__dict__)

執行結果:

1 #傳入正確類型的值

2

3 set方法4 set方法5 set方法6 {'__doc__': None, 'name': <__main__.typed object at>, '__dict__': , '__module__': '__main__', '__init__': , 'salary': <__main__.typed object at>, '__weakref__': , 'age': <__main__.typed object at>}7

8 #傳入錯誤類型的值,會報錯,并提示你傳入值的類型。

示例7:利用描述自定制property

1 classLazyproperty:2 def __init__(self,func):3 print('===========>',func)4 self.func=func5 def __get__(self,instance,owner):6 print('get')7 print('instance')8 print('owner')9 res=self.func(instance)10 returnres11 classRoom:12 def __init__(self,name,width,length):13 self.name=name14 self.width=width15 self.length=length16 @Lazyproperty17 defarea(self):18 return self.width *self.length19

20 r1=Room('廁所',1,1)21 print(r1.area)

執行結果:

1 get2 instance3 owner4 1

示例8:利用描述符實現延遲計算

1 classLazyproperty:2 def __init__(self,func):3 print('===========>',func)4 self.func=func5 def __get__(self,instance,owner):6 print('get')7 print('instance')8 print('owner')9 res=self.func(instance)10 returnres11 classRoom:12 def __init__(self,name,width,length):13 self.name=name14 self.width=width15 self.length=length16 @Lazyproperty17 defarea(self):18 return self.width *self.length19

20 r1=Room('廁所',1,1)21 print(r1.area)

示例9:非數據描述符

1 classLazyproperty:2 def __init__(self,func):3 self.func=func4

5 def __get__(self, instance, owner):6 print('get')7

8 if instance isNone:9 returnself10 res=self.func(instance)11 setattr(instance,self.func.__name__,res)12 returnres13

14 classRoom:15 def __init__(self,name,width,length):16 self.name=name17 self.width=width18 self.length=length19

20 @Lazyproperty21 defarea(self):22 return self.width *self.length23 @property24 defareal(self):25 return self.width *self.length26

27 r1=Room('廁所',1,1)28

29 print(r1.area)30 print(r1.__dict__)31

32 print(r1.area)33 print(r1.area)34 print(r1.area)35 print(r1.area)36 print(r1.area)37 print(r1.area)38 print(r1.area)39 print(r1.area)

執行結果:

1 get2 1

3 {'area': 1, 'length': 1, 'name': '廁所', 'width': 1}4 1

5 1

6 1

7 1

8 1

9 1

10 1

11 1

二十、元類(metaclass)

1、示例:

1 classFoo:2 pass

3

4 f1=Foo() #f1是通過Foo類實例化的對象

python中一切皆是對象,類本身也是一個對象,當使用關鍵字class的時候,python解釋器在加載class的時候就會創建一個對象(這里的對象指的是類而非類的實例)

上例可以看出f1是由Foo這個類產生的對象,而Foo本身也是對象,那它又是由哪個類產生的呢?

1 classFoo:2 pass

3

4 f1=Foo()5

6 print(type(f1)) #

7 print(type(Foo)) #類的類就是

8

9 classBar:10 pass

11 print(type(Bar)) #

執行結果:

1 #type函數可以查看類型,也可以用來查看對象的類,二者是一樣的。

2

3

4

2、什么是元類?

元類是類的類,是類的模板

元類是用來控制如何創建類的,正如類是創建對象的模板一樣

元類的實例為類,正如類的實例為對象(f1對象是Foo類的一個實例,Foo類是 type 類的一個實例)

type是python的一個內建元類,用來直接控制生成類,python中任何class定義的類其實都是type類實例化的對象

3、創建類的兩種方式

方式一:

1 classFoo:2 pass

3 print(Foo)4 print(Foo.__dict__)

執行結果:

1

2 {'__module__': '__main__', '__doc__': None, '__dict__': , '__weakref__': }

方式二:

1 #type就是類的類,用type()實例化的結果,就是產生一個類

2 #用type和class生成的類是一樣的效果。

3

4 def __init__(self,name,age):5 self.name=name6 self.age=age7

8 deftest(self):9 print('=======執行的是test=====>')10

11 FFo=type('FFo',(object,),{'x':1,'__init__':__init__,'test':test})12 print(FFo)13 #print(FFo.__dict__)

14

15 f1=FFo('alex',18)16 print(f1.x) #調的是類屬性

17 print(f1.name) #調name

18 f1.test() #調方法

執行結果:

1

2 1

3 alex4 =======執行的是test=====>

4、一個類沒有聲明自己的元類,默認他的元類就是type,除了使用元類type,用戶也可以通過繼承type來自定義元類。

示例:??自定制元類

1 classMyType(type):2 def __init__(self,a,b,c):3 print('元類的構造函數執行')4

5 def __call__(self, *args, **kwargs):6 obj=object.__new__(self) #object.__new__(Foo)-->f1

7 self.__init__(obj,*args,**kwargs) #Foo.__init__(f1,*arg,**kwargs)

8 returnobj9

10 class Foo(metaclass=MyType): #Foo=MyType(Foo,'Foo',(),{})---》__init__

11 def __init__(self,name):12 self.name=name #f1.name=name

13 f1=Foo('alex')

執行結果:

1 元類的構造函數執行

總結

以上是生活随笔為你收集整理的python对象属性在引用时前面需要加()_python基础-面向对象进阶的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。