Python基础入门之魔法方法与异常处理
作者:嘤嘤906 发布时间:2021-07-01 07:29:39
标签: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,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
0
投稿
猜你喜欢
- logging模块介绍Python的logging模块提供了通用的日志系统,熟练使用logging模块可以方便开发者开发第三方模块或者是自己
- 1、互动流通的活跃度是社区网站的关键,产品设计者大都需要在此猛下药。facebook有利用率最高的minifeed,myspace有“好友的
- 今天刚看到ChinaUI.com新改版的网站,觉得优艾网是越来越漂亮了,这次的变化的确是挺大的。一早大概的看了一下就关了,后来晚上又打开看时
- 回想自己从事Web方面的开发已经有6-7年,对于各种Web技术都已经非常熟悉.可是,身为程序员的我对于制作Web表单界面的事着实心痛。心痛1
- 本文实例讲述了Django框架设置cookies与获取cookies操作。分享给大家供大家参考,具体如下:在Django里面,使用Cooki
- Python 提供了如下两个函数来检查类型:issubclass(cls, class_or_tuple):检查 cls 是否为后一个类或元
- 代码如下:--销售冠军 --问题:在公司中,老板走进来,要一张每个地区销量前3名的销售额与销售员的报表 --- create t
- 本文实例为大家分享了python网络爬虫的笔记,供大家参考,具体内容如下(一) 三种网页抓取方法1、 正则
- s={ x1,x2,x3.....};集合有自动去重的功能,而且可以进行交并补运算,而且集合是无序的,每次打印的结果不一样,故不可以用元素下
- 最近看到市场上各种的文档格式转换软件,要么是收费、要么是有大量的广告。于是学习了一下 PyQt5 的页面操作,再加上了解 pandas 的使
- <% dim result,result1 str="ad_asp之家_nzlkjlkfjoj
- INI介绍INI是英文“初始化”(initialization)的缩写,被用来对操作系统或特定程序初
- 前言图像分割是指根据灰度、色彩、空间纹理、几何形状等特征把图像划分成若干个互不相交的区域。最简单的图像分割就是将物体从背景中分割出来1.图像
- 全选、全不选、反选这几个功能我们经常会用到,如我们可以用在文章列表管理页面,也可以用在音乐播放页面,使用全选我们可以很方便的进行批量操作,如
- 本文介绍了6个asp常用的判断函数的语法和使用方法,有IsArray 函数,IsDate 函数 ,IsEmpty 函数,IsNull 函数,
- 这次讨论一下关于select元素的一个问题,其实很早以前我就碰到过关于select元素的问题,这次做网站又被问到同样的问题,就是:一般div
- mktime()方法是localtime()反函数。它的参数是struct_time或全9元组,它返回一个浮点数,为了兼容时ti
- 1. 列表1.1 复制浅拷贝list_1 = [1, [22, 33, 44], (5, 6, 7), {"name":
- 一、读者指引 读者指引帮助你掌握本文的梗概。以免你看了大半才明白这编文章不适合你,给你造成视觉污染。如果你正在用ASP+XML写一些程序,或
- crtrl.py监控Apache服务器进程的Python 脚本!/usr/bin/env Python import os, sys, ti