目录
  • 一.魔法方法
    • 1.属性访问
    • 2.描述符
    • 3.定制序列
    • 5.生成器
  • 二.异常处理
    • 1.异常类型
    • 2.try-except语句
    • 3.try-finally语句
    • 4.raise语句
    • 5.丰富的else语句
  • 总结

    一.魔法方法

    1.属性访问

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

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

    魔法方法:

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

    ?1__getattr__(self,name)

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

    ?1__getattribute__(self,name)

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

    ?1__setattr__(self,name,value)

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

    ?1__delattr__(self,name)

    2.描述符

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

    ?1__get__(self,instance,owner)

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

    ?1__set__(self,instance,value)

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

    ?1__delete__(self,instance) ?123456789class 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.定制序列

    魔法方法:

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

    4.迭代器

    ?1234567for i in "FishC": print(i)FishC

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

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

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

    ?123456789101112string="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)失败。

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

    (2)AttributeError:尝试访问未知的对象属性。

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

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

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

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

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

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

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

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

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

    ?123451+'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:除数为零。

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

    2.try-except 语句

    ?12345678try: 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 语句

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

    4.raise 语句

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

    5.丰富的else语句

    ?12345678910111213try: 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))

    总结

    到此这篇关于Python基础入门之魔法方法与异常处理的文章就介绍到这了,更多相关Python魔法方法与异常处理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    您可能感兴趣的文章:
    • python的setattr函数实例用法
    • Python使用内置函数setattr设置对象的属性值
    • python中hasattr()、getattr()、setattr()函数的使用
    • Python __setattr__、 __getattr__、 __delattr__、__call__用法示例
    • Python __getattr__与__setattr__使用方法
    • 浅谈Python魔法方法
    • 详解Python常用的魔法方法
    • 详解Python魔法方法之描述符类
    • python魔法方法之__setattr__()