目錄
- 一、高級(jí)異常
- 二、環(huán)境管理器
- 三、運(yùn)算符重載
- 四、反向算術(shù)運(yùn)算符的重載
- 五、復(fù)合賦值算術(shù)運(yùn)算符的重載
- 六、比較運(yùn)算符的重載
- 七、位運(yùn)算符重載
- 八、反向位運(yùn)算符重載
- 九、復(fù)合賦值位運(yùn)算符重載
- 十、一元運(yùn)算符的重載
- 十一、in / not in 運(yùn)算符的重載
- 十二、索引和切片運(yùn)算符的重載
- 十三、slice 構(gòu)造函數(shù)
一、高級(jí)異常
回顧異常相關(guān)的語(yǔ)句:
try-except:用來(lái)捕獲異常的通知
try-finally:用來(lái)做一定要做的事
reise:用來(lái)發(fā)生異常通知
assert:用來(lái)根據(jù)條件來(lái)發(fā)出AssertionError類型的異常通知
with語(yǔ)句:
語(yǔ)句: with 表達(dá)式1 [as 變量1],表達(dá)式2 [as 變量2]:
語(yǔ)句塊
作用:使用于對(duì)資源進(jìn)行訪問(wèn)的場(chǎng)合,確保使用過(guò)程中不管是否發(fā)生異常,都會(huì)執(zhí)行必須的'清理'操作,并釋放資源
如:文件使用后自動(dòng)關(guān)閉;線程中鎖定的自動(dòng)獲取和釋放等
用with語(yǔ)句代替try-finally語(yǔ)句
def read_from_file(filename='info.txt'):
try:
with open(filename) as f:
print("正在讀取文件")
n = int(f.read())
print('n=', n)
print('文件已經(jīng)關(guān)閉')
# f = open(filename)
# try:
# print("正在讀取文件")
# n = int(f.read())
# print("n=", n)
# finally:
# f.close()
# print("文件已經(jīng)關(guān)閉")
except OSError:
print("文件打開失敗")
read_from_file()
二、環(huán)境管理器
1、類內(nèi)有__enter__和__exit__實(shí)例方法的類被稱為環(huán)境管理器
2、能夠用with語(yǔ)句管理的對(duì)象必須是環(huán)境管理器
3、 __enter__方法將在進(jìn)入with語(yǔ)句時(shí)被調(diào)用,并返回由as變量管理的對(duì)象
4、__exit__將在離開with語(yǔ)句時(shí)被調(diào)用,且可以用參數(shù)來(lái)判斷在離開with語(yǔ)句時(shí)是否有異常發(fā)生并做出相應(yīng)的處理
class A:
def __enter__(self):
print("已進(jìn)入with語(yǔ)句")
return self # 返回的對(duì)象將由 as綁定
def __exit__(self, exc_type, exc_val, exc_tb):
print("已離開with語(yǔ)句")
# a = A()
with A() as a:
print("這是with語(yǔ)句內(nèi)的一條語(yǔ)句")
int(input("請(qǐng)輸入整數(shù): "))
已進(jìn)入with語(yǔ)句
這是with語(yǔ)句內(nèi)的一條語(yǔ)句
請(qǐng)輸入整數(shù): 2
2.1、對(duì)象的屬性管理函數(shù)
1、getattr(obj, name[, default])從一個(gè)對(duì)象得到對(duì)象的屬性;getattr(x, 'y')等同于x.y;當(dāng)屬性不存在時(shí),如果給出default參數(shù),則返回default,如果沒(méi)有給出default則產(chǎn)生一個(gè)AttributeError錯(cuò)誤
2、hasattr(obj, name)用給定的name返回對(duì)象obj是否有此屬性,此種做法可以避免在getattr(obj, name)時(shí)引發(fā)錯(cuò)誤
3、setattr(obj, name, value)給對(duì)象obj的名為name的屬性設(shè)置相應(yīng)的值value, set(x,'y', v) 等同于 x.y = v
4、delattr(obj, name)刪除對(duì)象obj中的name屬性,delattr(x, 'y') 等同于 del x.y
class Car:
def __init__(self, c, b):
self.color, self.brand = c, b
def get_car_attr(self, attr_name):
'''此方法用于獲取對(duì)象的屬性,如果屬性名attr_name
在此對(duì)象內(nèi)不存在則返回 None
'''
return getattr(self, attr_name, None)
c1 = Car('黑色', 'Benz')
v = c1.get_car_attr('color')
# try:
# v = c1.__dict__['aaaaa']
# except KeyError:
# v = None
if v is None:
print("沒(méi)有顏色屬性")
else:
print("顏色是:", v)
getatter(obj,name[,default])
三、運(yùn)算符重載
讓自定義的類生成的對(duì)象(實(shí)例)能夠使用運(yùn)算符進(jìn)行操作
作用:讓自定義的類的實(shí)例像內(nèi)建對(duì)象一樣能夠運(yùn)行運(yùn)算符操作,讓程序簡(jiǎn)單易讀,對(duì)自定義的對(duì)象,將運(yùn)算符賦予新的運(yùn)算規(guī)則
3.1、算術(shù)運(yùn)算符的重載
__add__(self, rhs) self + rhs 加法
__sub__(self, rhs) self - rhs 減法
__mul__(self, rhs) self * rhs 乘法
__truediv__(self, rhs) self / rhs 除法
__floordiv__(self, rhs) self // rhs 地板除法
__mod__(self, rhs) self % rhs 求余
__pow__(self, rhs) self ** rhs 冪
注: rhs (right hands side) 右手邊
class MyNumber:
def __init__(self, v):
self.data = v
def __repr__(self):
return 'MyNumber(%d)' % self.data
# def myadd(self, other):
# v = self.data + other.data
# return MyNumber(v)
def __add__(self, other):
print("__add__被調(diào)用")
v = self.data + other.data
return MyNumber(v)
def __sub__(self, rhs):
v = self.data - rhs.data
return MyNumber(v)
n1 = MyNumber(100)
n2 = MyNumber(200)
# n3 = n1.myadd(n2)
# n3 = n1.__add__(n2)
n3 = n1 + n2 # __add__被調(diào)用
print(n3) # MyNumber(300)
n4 = n3 - n2
print(n4) # MyNumber(100)
class MyList:
def __init__(self, iterable):
self.data = list(iterable)
def __add__(self, rhs):
return MyList(self.data + rhs.data)
def __repr__(self):
return 'MyList(%r)' % self.data
def __mul__(self, rhs): # rhs 綁定整數(shù)
return MyList(self.data * rhs)
L1 = MyList([1, 2, 3])
L2 = MyList([4, 5, 6])
L3 = L1 + L2 # 等同于L1.__add__(L2)
print(L3) # MyList([1,2,3,4,5,6])
L4 = L2 + L1 # 等同于L2.__add__(L1)
print(L4) # MyList([4,5,6,1,2,3])
L5 = L1 * 2 # L1.__mul__(2)
print(L5) # MyList([1,2,3,1,2,3])
四、反向算術(shù)運(yùn)算符的重載
__radd__(self, lhs) lhs + self 加法
__rsub__(self, lhs) lhs - self 減法
__rmul__(self, lhs) lhs * self 乘法
__rtruediv__(self, lhs) lhs / self 除法
__rfloordiv__(self, lhs) lhs // self 地板除法
__rmod__(self, lhs) lhs % self 求余
__rpow__(self, lhs) lhs ** self 冪
class MyList:
def __init__(self, iterable):
self.data = list(iterable)
def __add__(self, rhs):
return MyList(self.data + rhs.data)
def __repr__(self):
return 'MyList(%r)' % self.data
def __mul__(self, rhs): # rhs 綁定整數(shù)
print('__mul__被調(diào)用')
return MyList(self.data * rhs)
def __rmul__(self, lhs):
print('__rmul__被調(diào)用')
return MyList(self.data * lhs)
L1 = MyList([1, 2, 3])
L2 = MyList([4, 5, 6])
L5 = L1 * 2 # L1.__mul__(2)
print(L5) # MyList([1,2,3,1,2,3])
L6 = 2 * L1 # 2.__mul__(L1)
print(L6)
五、復(fù)合賦值算術(shù)運(yùn)算符的重載
__iadd__(self, rhs) self += rhs 加法
__isub__(self, rhs) self -= rhs 減法
__imul__(self, rhs) self *= rhs 乘法
__itruediv__(self, rhs) self /= rhs 除法
__ifloordiv__(self, rhs) self //= rhs 地板除法
__imod__(self, rhs) self %= rhs 求余
__ipow__(self, rhs) self **= rhs 冪
class MyList:
def __init__(self, iterable):
print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
self.data = list(iterable)
def __add__(self, rhs):
print('__add__被調(diào)用')
return MyList(self.data + rhs.data)
def __repr__(self):
return 'MyList(%r)' % self.data
def __iadd__(self, rhs):
print("__iadd__被調(diào)用!!!!")
self.data.extend(rhs.data)
return self
L1 = MyList([1, 2, 3]) # aaaaaaaaaaaaaaaaaaaaaaaaaaaaa
L2 = MyList([4, 5, 6]) # aaaaaaaaaaaaaaaaaaaaaaaaaaaaa
L1 += L2 # 當(dāng)沒(méi)有__iadd__方法時(shí),等同于調(diào)用L1 = L1 + L2 __iadd__被調(diào)用!!!!
print(L1) # MyList([1, 2, 3, 4, 5, 6])
六、比較運(yùn)算符的重載
__lt__(self, rhs) self rhs 小于
__le__(self, rhs) self = rhs 小于等于
__gt__(self, rhs) self > rhs 大于
__ge__(self, rhs) self >= rhs 大于等于
__eq__(self, rhs) self == rhs 等于
__ne__(self, rhs) self != rhs 不等于
注:比較運(yùn)算符通常返回True或False
七、位運(yùn)算符重載
__invert__(self) ~ self 取反(一元運(yùn)算符)
__and__(self, rhs) self rhs 位與
__or__(self, rhs) self | rhs 位或
__xor__(self, rhs) self ^ rhs 位異或
__lshift__(self, rhs) self rhs 左移
__rshift__(self, rhs) self >> rhs 右移
八、反向位運(yùn)算符重載
__rand__(self, lhs) lhs self 位與
__ror__(self, lhs) lhs | self 位或
__rxor__(self, lhs) lhs ^ self 位異或
__rlshift__(self, lhs) lhs self 左移
__rrshift__(self, lhs) lhs >> self 右移
九、復(fù)合賦值位運(yùn)算符重載
__iand__(self, rhs) self = rhs 位與
__ior__(self, rhs) self |= rhs 位或
__ixor__(self, rhs) self ^= rhs 位異或
__ilshift__(self, rhs) self = rhs 左移
__irshift__(self, rhs) self >>= rhs 右移
十、一元運(yùn)算符的重載
__neg__(self) - self 負(fù)號(hào)
__pos__(self) + self 正號(hào)
__invert__(self) ~ self 取反
一元運(yùn)算符的重載方法:
class 類名:
def __xxx__(self):
class MyList:
def __init__(self, iterable):
print("__init__被調(diào)用")
self.data = list(iterable)
def __repr__(self):
return 'MyList(%r)' % self.data
def __neg__(self):
'''此方法用來(lái)制定 - self 返回的規(guī)則'''
# L = [-x for x in self.data]
L = (-x for x in self.data)
return MyList(L)
L1 = MyList([1, -2, 3, -4])
L2 = -L1
print(L2)
運(yùn)算符重載說(shuō)明:
運(yùn)算符重載不能改變運(yùn)算符的優(yōu)先級(jí)
Python類名最好用駝峰命名法:
- MyList MyRange 大駝峰(所有單詞首字母大寫,其余小寫)
- getStudentAge 小駝峰(第一個(gè)單詞首字母小寫,其它首字母大寫)
十一、in / not in 運(yùn)算符的重載
重載方法:
__contains__(self, e) e in self 成員運(yùn)算
class MyList:
def __init__(self, iterable):
print("__init__被調(diào)用")
self.data = list(iterable)
def __repr__(self):
return 'MyList(%r)' % self.data
def __contains__(self, e):
'''此方法用來(lái)實(shí)現(xiàn) in / not in 運(yùn)算符的重載'''
print("__contains__被調(diào)用")
for x in self.data:
if x == e:
return True
return False
L1 = MyList([1, -2, 3, -4])
if -2 in L1:
print('-2 在 L1 中')
else:
print('-2 不在 L1中')
# 當(dāng)MyList的類內(nèi)重載了__contains__方法,則not in也同時(shí)可用
if -3 not in L1:
print("-3 不在 L1中")
else:
print('-3 在 L2中')
十二、索引和切片運(yùn)算符的重載
__getitem__(self, i) x = self[i] 索引/切片取值
__setitem__(self, i, v) self[i] = v 索引/切片賦值
__delitem__(self, i) del self[i] del語(yǔ)句刪除索引等
作用:
讓自定義的類型的對(duì)象能夠支持索引和切片操作
class MyList:
def __init__(self, iterable):
print("__init__被調(diào)用")
self.data = list(iterable)
def __repr__(self):
return 'MyList(%r)' % self.data
def __getitem__(self, i):
print("__getitem__被調(diào)用, i=", i)
# if type(i) is not int:
# raise TypeError
return self.data[i]
def __setitem__(self, i, v):
print("__setitem__被調(diào)用, i=", i, 'v =', v)
self.data[i] = v # 修改data綁定的列表
L1 = MyList([1, -2, 3, -4])
v = L1[-1]
print(v)
L1[1] = 2 # 等同于調(diào)用 L1.__setitem__(1, 2)
print(L1)
# 以下操作會(huì)出錯(cuò)
# print(L1[100000000000])
# print(L1['hello'])
十三、slice 構(gòu)造函數(shù)
作用:用于創(chuàng)建一個(gè)Slice切片對(duì)象, 此對(duì)象存儲(chǔ)一個(gè)切片的起始值,終止值和步長(zhǎng)信息
slice(start, stop=None, step=None) 創(chuàng)建一個(gè)切片對(duì)象
slice的對(duì)象的屬性:
- s.start 切片起始值,默認(rèn)為None
- s.stop 切片終止值,默認(rèn)為None
- s.step 切片步長(zhǎng) ,默認(rèn)為None
class MyList:
def __init__(self, iterable):
print("__init__被調(diào)用")
self.data = list(iterable)
def __repr__(self):
return 'MyList(%r)' % self.data
def __getitem__(self, i):
print("__getitem__被調(diào)用, i=", i)
if type(i) is int:
print("正在做索引操作")
elif type(i) is slice:
print("正在做切片操作")
print("切片的起始值:", i.start)
print("切片的終止值:", i.stop)
print("切片的步長(zhǎng):", i.step)
else:
raise KeyError
return self.data[i]
L1 = MyList([1, -2, 3, -4, 5, -6])
print(L1[::2]) # 等同于調(diào)用L1[slice(None, None, 2)]
以上就是解析python高級(jí)異常和運(yùn)算符重載的詳細(xì)內(nèi)容,更多關(guān)于python 高級(jí)異常 運(yùn)算符重載的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:- Python的運(yùn)算符重載詳解
- Python運(yùn)算符重載詳解及實(shí)例代碼
- Python運(yùn)算符重載用法實(shí)例分析
- Python運(yùn)算符重載用法實(shí)例
- Python 捕獲代碼中所有異常的方法
- Python同時(shí)處理多個(gè)異常的方法
- 解決python ThreadPoolExecutor 線程池中的異常捕獲問(wèn)題
- 使用Python將Exception異常錯(cuò)誤堆棧信息寫入日志文件
- 解決Python 異常TypeError: cannot concatenate ''str'' and ''int'' objects
- Python 輸出詳細(xì)的異常信息(traceback)方式