Python基础入门之魔法方法与异常处理

作者:嘤嘤906 时间:2021-07-01 07:29:39 

一.魔法方法

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,name)

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))

来源:https://blog.csdn.net/weixin_63414347/article/details/121442319

标签:python,魔法方法,异常处理
0
投稿

猜你喜欢

  • 关于python中time和datetime的区别与用法

    2022-07-15 00:54:17
  • 解决python递归函数及递归次数受到限制的问题

    2023-12-01 01:49:35
  • python/sympy求解矩阵方程的方法

    2023-07-04 07:06:34
  • 使用python os模块复制文件到指定文件夹的方法

    2022-01-06 13:23:01
  • Python pytorch实现绘制一维热力图

    2022-04-03 21:09:14
  • python中.format()方法使用详解

    2021-07-19 03:38:07
  • pandas 实现分组后取第N行

    2023-02-09 11:11:40
  • pygame实现雷电游戏雏形开发

    2021-04-14 13:52:31
  • python中的信号通信 blinker的使用小结

    2023-07-31 10:05:10
  • python函数指定默认值的实例讲解

    2021-07-20 14:05:01
  • Python+Opencv实现表格边框线检测

    2023-08-11 04:55:14
  • Python爬虫之Scrapy环境搭建案例教程

    2023-05-29 19:07:49
  • Python统计文本词汇出现次数的实例代码

    2022-01-11 02:13:14
  • Python排序搜索基本算法之堆排序实例详解

    2021-07-10 12:35:30
  • Python3爬虫RedisDump的安装步骤

    2023-07-17 00:42:15
  • 通过实例学习Python Excel操作

    2021-01-21 21:55:12
  • CSS实现元素透明的那些事

    2009-09-07 12:22:00
  • 多栏自适应布局问题浅谈

    2010-08-16 12:56:00
  • Python找出文件中使用率最高的汉字实例详解

    2021-11-06 06:37:53
  • Python绘制雷达图时遇到的坑的解决

    2021-05-18 00:09:03
  • asp之家 网络编程 m.aspxhome.com