全栈python第十四天 python异常

多态 类方法 类属性

在类外面添加属性两种方式,类添加,实例添加

class Wash(object):
    pass


wash = Wash()
wash.pp = 100

print(wash.pp)

Wash.pp = 100
wash = Wash()
print(wash.pp)

异常

finall无论是否异常都要执行的代码

try:
    print(1/0)
except (NameError, ZeroDivisionError):
    print(f'捕获成功!')

# 捕获异常描述信息

try:
    # print(1/2)
    print(1/0)
except Exception as result:
    print(f'捕获成功!{result}')
else:
    print('我是else,程序没有异常')
import time

file_Name = 'test[备份].txt'
try:
    f = open(file_Name)
    try:
        while True:
            content = f.readline()
            if len(content) == 0:
                break
            time.sleep(2)
            print(content)
    except:
        print(f'程序意外终止!')
    finally:
        f.close()
        print(f'文件关闭')
except:
    print(f'不存在这个文件{file_Name}')

 

自定义异常

class ShowInputError(Exception):
    def __init__(self, length, count):
        self.length = length
        self.count = count

    def __str__(self):
        return f'你的密码长度{self.length},少于{self.count}字符'


passLen = 3

try:
    passWorld = input('请输入你的密码:')
    if len(passWorld) < 3:
        raise ShowInputError(len(passWorld), passLen)
except ShowInputError as e:
    print(e)
else:
    print('密码输入完成!')

 

Guess you like

Origin blog.csdn.net/qq_41179365/article/details/110122552