【Python教程】魔法方法与异常处理方法

所需工具:

Python

聪明的大脑

勤劳的双手

 

注意:本站只提供教程,不提供任何成品+工具+软件链接,仅限用于学习和研究。

 

一.魔法方法

1.属性访问

通常可以通过点(.)操作符的形式去访问对象的属性。

class C:
def __init__(self):
self.x='X-man'
c=C()
c.x
'X-man'
getattr(c , 'x' , '木有这个属性')
'X-man'
getattr(c , 'y' , '木有这个属性')
'木有这个属性'

魔法方法:

(1)定义当用户试图获取一个不存在的属性时的行为。

__getattr__(self,name)  

(2)定义当该类的属性被访问时的行为。

__getattribute__(self,name)

(3)定义当一个属性被设置时的行为。

__setattr__(self,name,value)

(4)定义当一个属性被删除时的行为。

__delattr__(self,n

2.描述符

(1)用于访问属性,它返回属性的值。

__get__(self,instance,owner)

(2)将在属性分配操作中调用,不返回任何内容。

__set__(self,instance,value)

(3)控制删除操作,不返回任何内容。

__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

字符串就是一个容器,同时也是一个迭代对象,for语句的作用就是触发其迭代功能,每次从容器里依次拿出一个数据,这就是迭代操作。

Python提供了两个BIF:iter()和next()。

对一个可迭代对象调用iter()就得到它的迭代器,调用next()迭代器就会返回下一个值。

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

5.生成器

对于调用一个普通的Python函数,一般是从函数的第一行代码开始执行,结束于return语句、异常或者所有语句执行完毕。

二.异常处理

1.异常类型

(1)AssertionError:断言语句(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:尝试访问未知的对象属性。

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:字典中查找一个不存在的关键字。

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:尝试访问一个不存在的变量。

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

(6)OSError:操作系统产生的异常。

(7)SyntaxError:Python的语法错误。

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

(8)TypeError:不同类型间的无效操作。

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:除数为零。

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

2.try-except 语句

try:
int('abc')
sum =1+'1'
f =open('我是一个不存在的文档.txt')
print(f.read())
f.close()
except (ValueError,TypeError,OSError) as reason:
print('出错\n错误原因是:'+str(reason)')

3.try-finally 语句

try:
f =open('我是一个不存在的文档.txt')
print(f.read())
sum=1+'1'
except:
print('出错啦')
finally:
f.close()

4.raise 语句

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

5.丰富的else语句


try:
int('abc')
except ValueError as reason:
print('出错啦:'+str(reason))
else:
print('没有任何异常!')

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

 

标签

发表评论