上下文協議(**)
import time
#上下文協議
class
runtime
:def
__enter__
(self)
: self.start_time = time.time(
)return self.start_time
def__exit__
(self, exc_type, exc_val, exc_tb)
: self.end = time.time(
) self.run_time = self.end - self.start_time
print
("run time is %s"
%self.run_time)
with runtime():
li =
for i in
range
(100000000):
with runtime():
l2 =
[i for i in
range
(100000000
)]
#__new__方法主要用來向記憶體中申請空間
class
earth
: a =
1#類屬性,所以任何乙個例項物件都有a屬性
def__new__
(cls,
*args,
**kwargs)
:print
(cls)
#cls就是類本身
ifnot
hasattr
(cls,
'_instance'):
#加了_或者__的變數名屬於私有屬性,一般不能夠輕易動它
cls._instance =
super()
.__new__(cls)
#父類向記憶體申請一塊空間
return cls._instance
def__init__
(self)
: self.name =
'earth'
#例項屬性
def__str__
(self)
:return
'this is __str__ %s'
%self.name
def__repr__
(self)
:return
'this is __repr__ %r'
%self.name
e = earth(
)a = earth(
)#引用的是同乙個物件
print
('一樣'
if e==a else
'不一樣'
)#此時列印e呼叫了str魔法方法
print
(e)#直接呼叫列印了repr魔法方法
e#也可以只定義repr魔法方法,這樣列印呼叫都是repr魔法方法
#序列型別需要滿足__len__,__getitem__,__setitem__,__delitem__不需要改變就不需要定義後兩個
class
indextuple
:def
__init__
(self,
*args)
: self.values =
tuple
([x for x in args]
) self.index =
tuple
(enumerate
(self.values)
)def
__len__
(self)
:return
len(self.values)
def__getitem__
(self, item)
:return self.index[item]
def__repr__
(self)
:return
str(self.values)
my_tuple = indextuple(1,
4,5,
2,6,
3,7)
print
(my_tuple)
print
(len
(my_tuple)
)print
(my_tuple[2]
)
class
number
:def
__init__
(self,end=10)
: self.start =
0 self.end = end
def__iter__
(self)
:return self
def__next__
(self)
: self.start+=
1if self.start >= self.end:
raise stopiteration
return self.start
nu = number(
)iter
(nu)
for i in
range(11
):print
(next
(nu)
)#變成可迭代的
a =iter([
1,2,
3,4,
6])next
(a)#加號也是魔法方法
a =12
print
(a.__add__(12)
)
上下文管理協議
class open def init self,name self.name name def enter self print 執行enter def exit self,exc type,exc val,exc tb print 執行exit with open a.txt as f with...
上下文協議管理
with obj as f 塊 1.with obj 觸發obj.enter 拿到返回值 2.as f f 返回值 3.with obj as f 等同於 f obj.enter 4.執行 塊 一 沒有異常的情況下,整個 塊執行完畢後去觸發 exit 它的三個引數都為none 二 有異常的情況下,從...
上下文管理協議
with open a.txt as f 開啟檔案,並自動關閉檔案 pass 上下文管理協議 class open def init self,name self.name name def enter self print 執行enter print self return self def ex...