脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python异常处理与反射相关问题总结

Python异常处理与反射相关问题总结

2021-12-03 10:36华青水上 Python

今天给大家带来的是关于Python的相关知识,文章围绕着Python异常处理与反射展开,文中有非常详细的介绍及代码示例,需要的朋友可以参考下

一、异常处理

在程序开发中如果遇到一些 不可预知的错误 或 你懒得做一些判断 时,可以选择用异常处理来做。

?
1
2
3
4
5
6
7
import requests
 
while True:
    url = input("请输入要下载网页地址:")
    res = requests.get(url=url)
    with open('content.txt', mode='wb') as f:
        f.write(res.content)

上述下载视频的代码在正常情况下可以运行,但如果遇到网络出问题,那么此时程序就会报错无法正常执行

?
1
2
3
4
5
try:
    res = requests.get(url=url)
except Exception as e:
    代码块,上述代码出异常待执行。
print("结束")
?
1
2
3
4
5
6
7
8
9
10
11
12
13
import requests
 
while True:
    url = input("请输入要下载网页地址:")
    
    try:
        res = requests.get(url=url)
    except Exception as e:
        print("请求失败,原因:{}".format(str(e)))
        continue
        
    with open('content.txt', mode='wb') as f:
        f.write(res.content)
?
1
2
3
4
5
6
7
8
9
num1 = input("请输入数字:")
num2 = input("请输入数字:")
try:
    num1 = int(num1)
    num2 = int(num2)
    result = num1 + num2
    print(result)
except Exception as e:
    print("输入错误")

以后常见的应用场景:

  • 调用微信的API实现微信消息的推送、微信支付等
  • 支付宝支付、视频播放等
  • 数据库 或 redis连接和操作
  • 调用第三方的视频播放发的功能,由第三方的程序出问题导致的错误。

异常处理的基本格式:

?
1
2
3
4
try:
    # 逻辑代码
except Exception as e:
    # try中的代码如果有异常,则此代码块中的代码会执行。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
try:
    # 逻辑代码
except Exception as e:
    # try中的代码如果有异常,则此代码块中的代码会执行。
finally:
    # try中的代码无论是否报错,finally中的代码都会执行,一般用于释放资源。
 
print("end")
 
"""
try:
    file_object = open("xxx.log")
    # ....
except Exception as e:
    # 异常处理
finally:
    file_object.close()  # try中没异常,最后执行finally关闭文件;try有异常,执行except中的逻辑,最后再执行finally关闭文件。
"""

1.1 异常细分

?
1
2
3
4
5
6
7
8
9
10
11
12
13
import requests
 
while True:
    url = input("请输入要下载网页地址:")
    
    try:
        res = requests.get(url=url)
    except Exception as e:
        print("请求失败,原因:{}".format(str(e)))
        continue
        
    with open('content.txt', mode='wb') as f:
        f.write(res.content)

之前只是简单的捕获了异常,出现异常则统一提示信息即可。如果想要对异常进行更加细致的异常处理,则可以这样来做:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import requests
from requests import exceptions
 
while True:
    url = input("请输入要下载网页地址:")
    try:
        res = requests.get(url=url)
        print(res)   
    except exceptions.MissingSchema as e:
        print("URL架构不存在")
    except exceptions.InvalidSchema as e:
        print("URL架构错误")
    except exceptions.InvalidURL as e:
        print("URL地址格式错误")
    except exceptions.ConnectionError as e:
        print("网络连接错误")
    except Exception as e:
        print("代码出现错误", e)
        
# 提示:如果想要写的简单一点,其实只写一个Exception捕获错误就可以了

如果想要对错误进行细分的处理,例如:发生Key错误和发生Value错误分开处理。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
try:
    # 逻辑代码
    pass
 
except KeyError as e:
    # 小兵,只捕获try代码中发现了键不存在的异常,例如:去字典 info_dict["n1"] 中获取数据时,键不存在。
    print("KeyError")
 
except ValueError as e:
    # 小兵,只捕获try代码中发现了值相关错误,例如:把字符串转整型 int("无诶器")
    print("ValueError")
 
except Exception as e:
    # 王者,处理上面except捕获不了的错误(可以捕获所有的错误)。
    print("Exception")

Python中内置了很多细分的错误,供你选择。

常见异常:
"""
AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
IOError 输入/输出异常;基本上是无法打开文件
ImportError 无法引入模块或包;基本上是路径问题或名称错误
IndentationError 语法错误(的子类) ;代码没有正确对齐
IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问n x[5]
KeyError 试图访问字典里不存在的键 inf['xx']
KeyboardInterrupt Ctrl+C被按下
NameError 使用一个还未被赋予对象的变量
SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
TypeError 传入对象类型与要求的不符合
UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
导致你以为正在访问它
ValueError 传入一个调用者不期望的值,即使值的类型是正确的
"""
更多异常:
"""
ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError
"""

1.2 自定义异常&抛出异常

上面都是Python内置的异常,只有遇到特定的错误之后才会抛出相应的异常。

其实,在开发中也可以自定义异常。

?
1
2
class MyException(Exception):
    pass
?
1
2
3
4
5
6
try:
    pass
except MyException as e:
    print("MyException异常被触发了", e)
except Exception as e:
    print("Exception", e)

上述代码在except中定义了捕获MyException异常,但他永远不会被触发。因为默认的那些异常都有特定的触发条件,例如:索引不存在、键不存在会触发IndexError和KeyError异常。

对于我们自定义的异常,如果想要触发,则需要使用:raise MyException()类实现。

?
1
2
3
4
5
6
7
8
9
10
11
12
class MyException(Exception):
    pass
 
 
try:
    # 。。。
    raise MyException()
    # 。。。
except MyException as e:
    print("MyException异常被触发了", e)
except Exception as e:
    print("Exception", e)
?
1
2
3
4
5
6
7
8
9
10
11
12
class MyException(Exception):
    def __init__(self, msg, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.msg = msg
 
 
try:
    raise MyException("xxx失败了")
except MyException as e:
    print("MyException异常被触发了", e.msg)
except Exception as e:
    print("Exception", e)
?
1
2
3
4
5
6
7
8
9
10
class MyException(Exception):
    title = "请求错误"
 
 
try:
    raise MyException()
except MyException as e:
    print("MyException异常被触发了", e.title)
except Exception as e:
    print("Exception", e)

案例一:你我合作协同开发,你调用我写的方法。

我定义了一个函数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
class EmailValidError(Exception):
    title = "邮箱格式错误"
 
class ContentRequiredError(Exception):
    title = "文本不能为空错误"
    
def send_email(email,content):
    if not re.match("\w+@live.com",email):
        raise EmailValidError()
    if len(content) == 0 :
        raise ContentRequiredError()
    # 发送邮件代码...
    # ...

你调用我写的函数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def execute():
    # 其他代码
    # ...
    
    try:
        send_email(...)
    except EmailValidError as e:
        pass
    except ContentRequiredError as e:
        pass
    except Exception as e:
        print("发送失败")
 
execute()
 
# 提示:如果想要写的简单一点,其实只写一个Exception捕获错误就可以了。

案例二:在框架内部已经定义好,遇到什么样的错误都会触发不同的异常。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import requests
from requests import exceptions
 
while True:
    url = input("请输入要下载网页地址:")
    try:
        res = requests.get(url=url)
        print(res)   
    except exceptions.MissingSchema as e:
        print("URL架构不存在")
    except exceptions.InvalidSchema as e:
        print("URL架构错误")
    except exceptions.InvalidURL as e:
        print("URL地址格式错误")
    except exceptions.ConnectionError as e:
        print("网络连接错误")
    except Exception as e:
        print("代码出现错误", e)
        
# 提示:如果想要写的简单一点,其实只写一个Exception捕获错误就可以了。

案例三:按照规定去触发指定的异常,每种异常都具备被特殊的含义。

Python异常处理与反射相关问题总结

1.4 特殊的finally

?
1
2
3
4
5
6
7
8
try:
    # 逻辑代码
except Exception as e:
    # try中的代码如果有异常,则此代码块中的代码会执行。
finally:
    # try中的代码无论是否报错,finally中的代码都会执行,一般用于释放资源。
 
print("end")

当在函数或方法中定义异常处理的代码时,要特别注意finally和return

?
1
2
3
4
5
6
7
8
9
def func():
    try:
        return 123
    except Exception as e:
        pass
    finally:
        print(666)
        
func()

在try或except中即使定义了return,也会执行最后的finally块中的代码。

二、反射

反射,提供了一种更加灵活的方式让你可以实现去 对象 中操作成员(以字符串的形式去 对象 中进行成员的操作)。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Person(object):
    
    def __init__(self,name,wx):
        self.name = name
        self.wx = wx
    
    def show(self):
        message = "姓名{},微信:{}".format(self.name,self.wx)
        
        
user_object = Person("华青水上","hqss666")
 
 
# 对象.成员 的格式去获取数据
user_object.name
user_object.wx
user_object.show()
 
# 对象.成员 的格式无设置数据
user_object.name = "华青水上"
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
user = Person("华青水上","hqss666")
 
# getattr 获取成员
getattr(user,"name") # user.name
getattr(user,"wx")   # user.wx
 
 
method = getattr(user,"show") # user.show
method()
# 或
getattr(user,"show")()
 
# setattr 设置成员
setattr(user, "name", "华青水上") # user.name = "华青水上"

Python中提供了4个内置函数来支持反射:

getattr,去对象中获取成员

?
1
2
v1 = getattr(对象,"成员名称")
v2 = getattr(对象,"成员名称", 不存在时的默认值)

setattr,去对象中设置成员

?
1
setattr(对象,"成员名称",值)

hasattr,对象中是否包含成员

?
1
v1 = hasattr(对象,"成员名称") # True/False

delattr,删除对象中的成员

?
1
delattr(对象,"成员名称")

以后如果再遇到 对象.成员 这种编写方式时,均可以基于反射来实现。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Account(object):
 
    def login(self):
        pass
 
    def register(self):
        pass
 
    def index(self):
        pass
 
    
def run(self):
    name = input("请输入要执行的方法名称:") # index register login xx run ..
    
    account_object = Account()
    method = getattr(account_object, name,None) # index = getattr(account_object,"index")
    
    if not method:
        print("输入错误")
        return
    method()

2.1 一些皆对象

在Python中有这么句话:一切皆对象。 每个对象的内部都有自己维护的成员。

对象是对象

?
1
2
3
4
5
6
7
8
9
10
11
12
class Person(object):
    
    def __init__(self,name,wx):
        self.name = name
        self.wx = wx
    
    def show(self):
        message = "姓名{},微信:{}".format(self.name,self.wx)
        
        
user_object = Person("华青水上","hqss666")
user_object.name

类是对象

?
1
2
3
4
5
class Person(object):
    title = "武沛齐"
 
Person.title
# Person类也是一个对象(平时不这么称呼)

模块是对象

?
1
2
3
4
import re
 
re.match
# re模块也是一个对象(平时不这么称呼)。

由于反射支持以字符串的形式去对象中操作成员【等价于 对象.成员 】,所以,基于反射也可以对类、模块中的成员进行操作。

简单粗暴:只要看到 xx.oo 都可以用反射实现。

?
1
2
3
4
5
6
7
class Person(object):
    title = "华青水上"
 
v1 = Person.title
print(v1)
v2 = getattr(Person,"title")
print(v2)
?
1
2
3
4
5
6
7
8
import re
 
v1 = re.match("\w+","dfjksdufjksd")
print(v1)
 
func = getattr(re,"match")
v2 = func("\w+","dfjksdufjksd")
print(v2)

2.2 import_module + 反射

?
1
2
3
4
5
6
# 导入模块
from importlib import import_module
 
m = import_module("random")
 
v1 = m.randint(1,100)

在Python中如果想要导入一个模块,可以通过import语法导入;企业也可以通过字符串的形式导入。

示例一:

?
1
2
3
4
# 导入模块
import random
 
v1 = random.randint(1,100)

示例二:

?
1
2
# 导入模块exceptions
from requests import exceptions as m
?
1
2
3
# 导入模块exceptions
from importlib import import_module
m = import_module("requests.exceptions")

示例三:

?
1
2
# 导入模块exceptions,获取exceptions中的InvalidURL类。
from requests.exceptions import InvalidURL
?
1
2
3
# 错误方式
from importlib import import_module
m = import_module("requests.exceptions.InvalidURL") # 报错,import_module只能导入到模块级别
?
1
2
3
4
5
# 导入模块
from importlib import import_module
m = import_module("requests.exceptions")
# 去模块中获取类
cls = m.InvalidURL

在很多项目的源码中都会有 import_modulegetattr 配合实现根据字符串的形式导入模块并获取成员,例如:

?
1
2
3
4
5
6
7
8
9
10
11
from importlib import import_module
 
path = "openpyxl.utils.exceptions.InvalidFileException"
 
module_path,class_name = path.rsplit(".",maxsplit=1) # "openpyxl.utils.exceptions"   "InvalidFileException"
 
module_object = import_module(module_path)
 
cls = getattr(module_object,class_name)
 
print(cls)

我们在开发中也可以基于这个来进行开发,提高代码的可扩展性。

至此Python进阶中面向对象之异常处理与反射总结完毕,如有不当之处,欢迎指正!

到此这篇关于Python异常处理与反射相关问题总结的文章就介绍到这了,更多相关Python异常处理与反射内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/r1141207831/article/details/117910422

延伸 · 阅读

精彩推荐