python异常处理与with用法day11/早上

try:                           #尝试运行,执行try里的代码直到遇到错误再执行except
    a=[1,2]
    print(a[0])
    raise KeyError("键错误")  #抛出异常
    print(a[3])
except KeyError as e:          #捕获异常
    print("出现错误",e)
else:                          #执行完try的的语句后不出现错误执行else
    print("没有出现错误执行这里")
finally:                       #有无异常最后都执行finally
    print("有没有错误都执行这里")

#with可以打开文件,文件操作完毕后自动关闭文档

with open("a.txt","w") as f:
    f.write("123")
with open("a.txt","r") as f1:
    c=f1.read()
    print(c)

#写一个程序证明多态
class Dog():
    def jiao(self):
        print("旺旺")
class Cat():
    def jiao(self):
        print("喵喵")
class Pig():
    def jiao(self):
        print("哈哈")
def say(x):
    x.jiao()
a=Dog()
b=Cat()
c=Pig()
say(a)
say(b)
say(c)

猜你喜欢

转载自blog.csdn.net/qq_39112101/article/details/88179448
今日推荐