溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python基礎(chǔ)中的魔法方法與異常處理是怎樣的

發(fā)布時(shí)間:2021-11-22 09:19:35 來(lái)源:億速云 閱讀:132 作者:柒染 欄目:開(kāi)發(fā)技術(shù)

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)Python基礎(chǔ)中的魔法方法與異常處理是怎樣的,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

一.魔法方法

1.屬性訪問(wèn)

通??梢酝ㄟ^(guò)點(diǎn)(.)操作符的形式去訪問(wèn)對(duì)象的屬性。

class C:
	def __init__(self):
		self.x='X-man'
c=C()
c.x
'X-man'
getattr(c , 'x' , '木有這個(gè)屬性')
'X-man'
getattr(c , 'y' , '木有這個(gè)屬性')
'木有這個(gè)屬性'

魔法方法:

(1)定義當(dāng)用戶試圖獲取一個(gè)不存在的屬性時(shí)的行為。

__getattr__(self,name)	

(2)定義當(dāng)該類的屬性被訪問(wèn)時(shí)的行為。

__getattribute__(self,name)

(3)定義當(dāng)一個(gè)屬性被設(shè)置時(shí)的行為。

__setattr__(self,name,value)

(4)定義當(dāng)一個(gè)屬性被刪除時(shí)的行為。

__delattr__(self,name)

2.描述符

(1)用于訪問(wèn)屬性,它返回屬性的值。

__get__(self,instance,owner)

(2)將在屬性分配操作中調(diào)用,不返回任何內(nèi)容。

__set__(self,instance,value)

(3)控制刪除操作,不返回任何內(nèi)容。

__delete__(self,instance)
class MyDescriptor:
    def __get__(self,instance,owner):
        print("getting...",self,instance,owner)
    def __set__(self,instance,value):
        print("setting...",self,instance,value)
    def __delete__(self,instance):
        print("deleting...",self,instance)
class Test:
    x =MyDescriptor()

3.定制序列

魔法方法:

__len__(self)
__getitem__(self,key)
__setitem__(self,key,value)
__delitem__(self,key)
__iter__(self)
__reversed__(self)
__contains__(self,item)

4.迭代器

for i in "FishC":
	print(i)
F
i
s
h
C

字符串就是一個(gè)容器,同時(shí)也是一個(gè)迭代對(duì)象,for語(yǔ)句的作用就是觸發(fā)其迭代功能,每次從容器里依次拿出一個(gè)數(shù)據(jù),這就是迭代操作。

Python提供了兩個(gè)BIF:iter()和next()。

對(duì)一個(gè)可迭代對(duì)象調(diào)用iter()就得到它的迭代器,調(diào)用next()迭代器就會(huì)返回下一個(gè)值。

string="FishC"
it=iter(string)
next(it)
'F'
next(it)
'i'
next(it)
's'
next(it)
'h'
next(it)
'C'

5.生成器

對(duì)于調(diào)用一個(gè)普通的Python函數(shù),一般是從函數(shù)的第一行代碼開(kāi)始執(zhí)行,結(jié)束于return語(yǔ)句、異?;蛘咚姓Z(yǔ)句執(zhí)行完畢。

二.異常處理

1.異常類型

(1)AssertionError:斷言語(yǔ)句(assert)失敗。

my_list=["小甲魚"]
assert len(my_list)>0
my_list.pop()
'小甲魚'
assert len(my_list)>0
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    assert len(my_list)>0
AssertionError

(2)AttributeError:嘗試訪問(wèn)未知的對(duì)象屬性。

my_list=[]
my_list.fishc
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    my_list.fishc
AttributeError: 'list' object has no attribute 'fishc'

(3)IndexError:索引超出序列的范圍。

my_list=[1,2,3]
my_list[3]
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    my_list[3]
IndexError: list index out of range

(4)KeyError:字典中查找一個(gè)不存在的關(guān)鍵字。

my_dict={"one":1,"two":2}
my_dict["three"]
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    my_dict["three"]
KeyError: 'three'

(5)NameError:嘗試訪問(wèn)一個(gè)不存在的變量。

fishc
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    fishc
NameError: name 'fishc' is not defined

(6)OSError:操作系統(tǒng)產(chǎn)生的異常。

(7)SyntaxError:Python的語(yǔ)法錯(cuò)誤。

print"I love fishc.com"
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?

(8)TypeError:不同類型間的無(wú)效操作。

1+'1'
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    1+'1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

(9)ZeroDivisionError:除數(shù)為零。

5/0
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    5/0
ZeroDivisionError: division by zero

2.try-except 語(yǔ)句

try:
    int('abc')
    sum =1+'1'
    f =open('我是一個(gè)不存在的文檔.txt')
    print(f.read())
    f.close()
except (ValueError,TypeError,OSError) as reason:
    print('出錯(cuò)\n錯(cuò)誤原因是:'+str(reason)')

3.try-finally 語(yǔ)句

try:
    f =open('我是一個(gè)不存在的文檔.txt')
print(f.read())
	sum=1+'1'
except:
	print('出錯(cuò)啦')
finally:
	f.close()

4.raise 語(yǔ)句

raise ZeroDivisionError5/0
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    5/0
ZeroDivisionError: division by zero

5.豐富的else語(yǔ)句

try:
    int('abc')
except ValueError as reason:
    print('出錯(cuò)啦:'+str(reason))
else:
    print('沒(méi)有任何異常!')

try:
    with open('data.txt','w') as f:
        for each_line in f:
            print(each_line)
except OSError as reason:
    print('出錯(cuò)啦:'+str(reason))

上述就是小編為大家分享的Python基礎(chǔ)中的魔法方法與異常處理是怎樣的了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI