Python抽象及异常处理
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python抽象及异常处理相关的知识,希望对你有一定的参考价值。
#面向对象:多态、封装、继承
#1 多态:意味着即使不知道变量所引用的对象类型是什么,还是能对他进行操作,而且也会根据他的不同类型表现出不同的行为
#多态和方法
from random import choice
x = choice([‘Hello World‘,[‘1‘,‘1‘,‘1‘,‘2‘,‘3‘]])
print(x)
print(x.count(‘1‘))#1出现的次数 不需要检测类型 只需要知道有conut这个方法
#多态的多种形式:+运算对字符串、数字起作用
#2 封装对全局作用域中的其他区域隐藏多余信息
#3 继承:不想代码重复 使用原来的代码
#4 类
#创建类
_metaclass_= type
class Person:
def setname(self,name):
self.name = name
def getname(self):
return self.name
def greet(self):
print("Hello I am %s"%self.name)
#调用类
foo = Person()
bar = Person()
foo.setname("1234567")
bar.setname("7891213")
foo.greet()
bar.greet()
print(foo.name,bar.name)
#-------------------------输出结果----------------------------------#
"""
C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test6.py
Hello World
0
Hello I am 1234567
Hello I am 7891213
1234567 7891213
"""
#特性、函数、方法
class Class:
def method(self):
print("I am self")
def fuction():
print("I don‘t...")
obj = Class()
obj.method()
obj.method = fuction # 特性绑定到一个普通的函数上
obj.method()
test = obj.method #test变量引用绑定方法上
test()
#-------------------------输出结果----------------------------------#
"""
I am self
I don‘t...
I don‘t..
"""
#私有特性:为了让特性和方法变成私有(外部不能访问),只要在名字前加上双下划线
#指定超类
class Filter:
def init(self):
self.blocked=[]
def filter(self,test):
return [x for x in test if x not in self.blocked]
def _test(self):
print("我是私有的")
class ChildFilter(Filter):#指定超类 ChildFilter为Filter的子类
def init(self):
print("我是子类 正在重写父类方法")
self.blocked=[‘as‘]
f = Filter()
f.init()
print(f.filter([1,2,3]))
f1 = ChildFilter()
f1.init()
print(f1.filter([1,23,56]))
#-------------------------输出结果----------------------------------#
"""
C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test6.py
[1, 2, 3]
我是子类 正在重写父类方法
[1, 23, 56]
"""
#捕获异常
try:
x = 5
y = 0
print(x/y)
except ZeroDivisionError:
print("分母不能为0")
#-------------------------输出结果----------------------------------#
"""
C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test6.py
分母不能为0
"""
# raise
class MuffledCalculator:
muffed = False
def calc(self,expr):
try:
return eval(expr)
except ZeroDivisionError:
if self.muffed:
print("Division is zero by illegal")
else:
raise #
cal = MuffledCalculator()
print(cal.calc(‘10/2‘))
cal.muffed = True #打开屏蔽机制
print("hehehe-->",cal.calc(‘10/0‘))
#-------------------------输出结果----------------------------------#
"""
C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test6.py
分母不能为0
5.0
Division is zero by illegal
hehehe--> None
"""
#用一个块捕捉两个异常
try:
x = input("input your first num:")
y = input("input your second num:")
print(x/y)
except(ZeroDivisionError,TypeError,NameError).e:
print("Your Num were bug")
print(e)
while True:
try:
x = int(input("input your first num:"))
y= int(input("input your second num:"))
value = x/y
print(value)
except Exception.e:
print("Exception ",e)
print("try again")
else:
break
"""
#-------------------------输出结果----------------------------------#
C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test6.py
input your first num:10input your second num:33.3333333333333335C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test6.pyinput your first num:10input your second num:0Traceback (most recent call last): File "D:/Python-Test/qiubai/qiubai/Test6.py", line 145, in <module> value = x/yZeroDivisionError: division by zeroDuring handling of the above exception, another exception occurred:Traceback (most recent call last): File "D:/Python-Test/qiubai/qiubai/Test6.py", line 147, in <module> except Exception.e:AttributeError: type object ‘Exception‘ has no attribute ‘e‘"""while True: try: x = int(input("input your first num:")) y= int(input("input your second num:")) value = x/y print(value) except: print("try again") else:#只有程序没有异常情况才会退出 只要错误发生,程序会不断重新要求输入 break"""#-------------------------输出结果----------------------------------#C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test6.pyinput your first num:10input your second num:0try againinput your first num:10input your second num:33.3333333333333335"""#Finally:x = Nonetry: x = x / 0finally:#通常用于关闭文件或网络套接字 print(‘Clean up .....‘) del x #程序崩溃之前 对于x的变量清理 """C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test6.pyClean up .....Traceback (most recent call last): File "D:/Python-Test/qiubai/qiubai/Test6.py", line 203, in <module> x = x / 0TypeError: unsupported operand type(s) for /: ‘NoneType‘ and ‘int‘"""
以上是关于Python抽象及异常处理的主要内容,如果未能解决你的问题,请参考以下文章