python3中format方法_python3 自定制format格式化,很多很多的内置方法。。。。。。。。。。。...
1.哈哈哈,說實話,前面的foamat格式化并不是很懂:
舉例:
1 date_format={2 "y-m-d":"{0.year}年{0.month}月{0.day}日",3 "y:m:d":"{0.year}:{0.month}:{0.day}"
4 }5 classDate():6 def __init__(self,year,month,day):7 self.year=year8 self.month=month9 self.day=day10 def __format__(self, format_spec):11 if not format_spec or format_spec not indate_format:12 return "請重新輸入正確的日期格式"
13 else:14 fm=date_format[format_spec]15 returnfm.format(self)16 d=Date(2018,9,26)17 print(format(d,"y:m:d"))18 print(format(d,"y-m-d"))19 print(format(d,"qwe"))20
21
22
23 #############
24 2018:9:26
25 2018年9月26日26 請重新輸入正確的日期格式
View Code
2.__slots__
作用:定義__slots__后,__slots__就會為實例使用一種更加緊湊的內(nèi)部表示。實例通過一個很小的固定大小的數(shù)組來構建,而不是為每個實例定義一個字典,這跟元組或列表很類似。在__slots__中列出的屬性名在內(nèi)部被映射到這個數(shù)組的指定小標上。使用__slots__一個不好的地方就是不能再給實例添加新的屬性了,只能使用在__slots__中定義的那些屬性名。定義了__slots__后的類不再 支持一些普通類特性了,比如多繼承。大多數(shù)情況下,應該只在那些經(jīng)常被使用到 的用作數(shù)據(jù)結構的類上定義__slots__比如在程序中需要創(chuàng)建某個類的幾百萬個實例對象 。
關于__slots__的一個常見誤區(qū)是它可以作為一個封裝工具來防止用戶給實例增加新的屬性。盡管使用__slots__可以達到這樣的目的,但是這個并不是它的初衷。更多的是用來作為一個內(nèi)存優(yōu)化工具。
舉例:定義它了之后,就沒有屬性字典了(報錯)。
1 classAa():2 _slots__=__slots__=['name','age'] #就是等于{'name':None,'age':None}
3 print("啦啊啊啊啊啊啊啊啦啦啦,是時候表演真正的技術了")4 a=Aa()5 print(a.__dict__)6
7 ############
8
9 啦啊啊啊啊啊啊啊啦啦啦,是時候表演真正的技術了10 Traceback (most recent call last):11 File "E:/Python/_demo/_demo1.py", line 560, in
12 print(a.__dict__)13 AttributeError: 'Aa' object has no attribute '__dict__'
View Code
1 classAa():2 _slots__=__slots__=['name','age'] #就是等于{'name':None,'age':None}
3 print("啦啊啊啊啊啊啊啊啦啦啦,是時候表演真正的技術了")4 a=Aa()5 a.name="小豬豬"
6 a.age=18
7 print(a.name)8 print(a.age)9 print(Aa.__slots__)10 print(a.__slots__)11
12 ################
13
14 啦啊啊啊啊啊啊啊啦啦啦,是時候表演真正的技術了15 小豬豬16 18
17 ['name', 'age']18 ['name', 'age']
View Code
賦值其中沒有定義的屬性報錯:
1 classAa():2 _slots__=__slots__=['name','age'] #就是等于{'name':None,'age':None}
3 print("啦啊啊啊啊啊啊啊啦啦啦,是時候表演真正的技術了")4 a=Aa()5 a.gender="女"
6 print(a.gender)7 print(Aa.__slots__)8 print(a.__slots__)9
10 #################
11 啦啊啊啊啊啊啊啊啦啦啦,是時候表演真正的技術了12 Traceback (most recent call last):13 File "E:/Python/_demo/_demo1.py", line 560, in
14 a.gender="女"
15 AttributeError: 'Aa' object has no attribute 'gender'
View Code
3.__doc__
描述信息:不能被繼承
1 classAa():2 '我是描述信息'
3 print(">>>>>>>>>>>>>>>>>>>>>>")4 classBb(Aa):5 print("<<<<<<<<<<<<<<<<<<<<<<<<
10
11
12 #########
13 >>>>>>>>>>>>>>>>>>>>>>
14 <<<<<<<<<<<<<<<<<<<<<<<<<
15 我是描述信息16 None
View Code
4.
__module__ 表示當前操作的對象在那個模塊
__class__ ? ? 表示當前操作的對象的類是什么
1 from demo3.demo2 importC2
3 c=C()4 print(c.__module__)5 print(c.__class__)6
7
8 ########
9 demo3.demo210
View Code
5.__call__
對象后面加括號,觸發(fā)執(zhí)行。
注:構造方法的執(zhí)行是由創(chuàng)建對象觸發(fā)的,即:對象 = 類名() ;而對于 __call__ 方法的執(zhí)行是由對象后加括號觸發(fā)的,即:對象() 或者 類()
1 classFoo:2
3 def __init__(self):4 pass
5
6 def __call__(self, *args, **kwargs):7
8 print('__call__')9
10
11 obj = Foo() #執(zhí)行 __init__
12 obj() #執(zhí)行 __call__
13
14
15 ###############
16 __call__
View Code
6.
__next__和__iter__實現(xiàn)迭代器協(xié)議
1 classFoo:2 def __init__(self,n):3 self.n=n4 def __iter__(self):5 returnself6
7 def __next__(self):8 if self.n == 13:9 raise StopIteration('終止了')10 self.n+=1
11 returnself.n12
13 f1=Foo(10)14
15 for i in f1: #obj=iter(f1)------------>f1.__iter__()
16 print(i) #obj.__next_()
17
18 ####################
19 11
20 12
21 13
View Code
7.?描述符(__get__,__set__,__delete__)
(1)描述符是什么:描述符本質(zhì)就是一個新式類,在這個新式類中,至少實現(xiàn)了__get__(),__set__(),__delete__()中的一個,這也被稱為描述符協(xié)議.
__get__():調(diào)用一個屬性時,觸發(fā)
__set__():為一個屬性賦值時,觸發(fā)
__delete__():采用del刪除屬性時,觸發(fā)
包含這三個方法的新式類稱為描述符,由這個類產(chǎn)生的實例進行屬性的調(diào)用/賦值/刪除,并不會觸發(fā)這三個方法
1 #####定義一個描述符
2 classAoo():3 def __get__(self, instance, owner):4 print("執(zhí)行__get__方法啦")5 def __set__(self, instance, value):6 print("執(zhí)行__set__方法啦")7 def __delete__(self, instance):8 print("執(zhí)行__delete__方法啦")
View Code
(2)描述符的作用:是用來代理另外一個類的屬性的(必須把描述符定義成這個類的類屬性,不能定義到構造函數(shù)中)
1 #####定義一個描述符
2 classAoo():3 def __get__(self, instance, owner):4 print("執(zhí)行__get__方法啦")5 def __set__(self, instance, value):6 print("執(zhí)行__set__方法啦")7 def __delete__(self, instance):8 print("執(zhí)行__delete__方法啦")9
10 classBoo():11 i=Aoo()##################定義到類屬性里面喔
12 def __init__(self,n):13 self.i=n
View Code
(3)描述符分兩種
一 數(shù)據(jù)描述符:至少實現(xiàn)了__get__()和__set__()
非數(shù)據(jù)描述符:沒有實現(xiàn)__set__()
(4)注意事項:
一 描述符本身應該定義成新式類,被代理的類也應該是新式類
二 必須把描述符定義成這個類的類屬性,不能為定義到構造函數(shù)中
三 要嚴格遵循該優(yōu)先級,優(yōu)先級由高到底分別是
1.類屬性
2.數(shù)據(jù)描述符
3.實例屬性
4.非數(shù)據(jù)描述符
5.找不到的屬性觸發(fā)__getattr__()
此處差個示例:
啦啦啦啦啦啦啦
7.__enter__和__exit__
(1)上下文管理協(xié)議,即with語句,為了讓一個對象兼容with語句,必須在這個對象的類中聲明__enter__和__exit__方法
1 #with open("a.txt","rb") as f:
2 #pass
3 ## open("a.txt","rb")這個就是類似于實例化一個對象,
4 ## as f對象重新命名為f
View Code
(2)沒有異常的情況下,整個代碼塊運行完畢后去觸發(fā)__exit__,它的三個參數(shù)都為None
1 classAa():2 def __init__(self,name):3 self.name=name4 def __enter__(self):5 print("__enter__執(zhí)行了")6 def __exit__(self, exc_type, exc_val, exc_tb):7 print("啦啦啦,被我打敗了")8 print(exc_type)9 print(exc_val)10 print(exc_tb)11 with Aa("a.txt") as f:12 print(f)13
14
15
16 ###################
17 __enter__執(zhí)行了
18 None19 啦啦啦,被我打敗了20 None21 None22 None
View Code
(3)有異常的情況下,從異常出現(xiàn)的位置直接觸發(fā)__exit__
如果__exit__的返回值為True,代表吞掉了異常(不會出現(xiàn)報錯)
__exit__的的運行完畢就代表了整個with語句的執(zhí)行完畢
1 classAa():2 def __init__(self,name):3 self.name=name4 def __enter__(self):5 print("__enter__執(zhí)行了")6 def __exit__(self, exc_type, exc_val, exc_tb):7 print("啦啦啦,被我打敗了")8 #print(exc_type)
9 #print(exc_val)
10 #print(exc_tb)
11 returnTrue12 with Aa("a.txt") as f:13 print("》》》》》》》》")14 print(f.name)15
16 #################
17 __enter__執(zhí)行了
18 》》》》》》》》19 啦啦啦,被我打敗了
View Code
(4)有異常的情況下,從異常出現(xiàn)的位置直接觸發(fā)__exit__
如果__exit__的返回值不為True,代表吐出了異常
__exit__的的運行完畢就代表了整個with語句的執(zhí)行完畢
1 classAa():2 def __init__(self,name):3 self.name=name4 def __enter__(self):5 print("__enter__執(zhí)行了")6 def __exit__(self, exc_type, exc_val, exc_tb):7 print("啦啦啦,被我打敗了")8 #print(exc_type)
9 #print(exc_val)
10 #print(exc_tb)
11 return False###簡單粗暴,直接為false
12 with Aa("a.txt") as f:13 print("》》》》》》》》")14 print(f.name)15
16 ##################
17 Traceback (most recent call last):18 File "E:/Python/_demo/_demo1.py", line 612, in
19 print(f.name)20 AttributeError: 'NoneType' object has no attribute 'name'
21 __enter__執(zhí)行了
22 》》》》》》》》23 啦啦啦,被我打敗了
View Code
__exit__的的運行完畢就代表了整個with語句的執(zhí)行完畢,后面的代碼則不會運行了。
1 classAa():2 def __init__(self,name):3 self.name=name4 def __enter__(self):5 print("__enter__執(zhí)行了")6 def __exit__(self, exc_type, exc_val, exc_tb):7 print("啦啦啦,被我打敗了")8 #print(exc_type)
9 #print(exc_val)
10 #print(exc_tb)
11 return False###簡單粗暴,直接為false
12 with Aa("a.txt") as f:13 print("》》》》》》》》")14 print(f.name)15 print("》》》》》》》》》》????????")16 print("》》》》》》》》》》。。")17 print("》》》》》》》》》》????????")18 print("》》》》》》》》》》。。")19
20 ########################################
21 __enter__執(zhí)行了
22 》》》》》》》》23 啦啦啦,被我打敗了24 Traceback (most recent call last):25 File "E:/Python/_demo/_demo1.py", line 612, in
26 print(f.name)27 AttributeError: 'NoneType' object has no attribute 'name'
View Code
總結
以上是生活随笔為你收集整理的python3中format方法_python3 自定制format格式化,很多很多的内置方法。。。。。。。。。。。...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 求一个阳光的个性签名!
- 下一篇: mysql 当前id前后几个,使用mys