1. 程式人生 > >Python抽象及異常處理

Python抽象及異常處理

訪問 崩潰 span peer test all 機制 出現 import

#面向對象:多態、封裝、繼承
#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抽象及異常處理