Python Abstraction and exception handling

Source: Internet
Author: User

#面向对象: polymorphism, encapsulation, inheritance
#1 polymorphism: It means that even if you don't know what type of object the variable refers to, you can manipulate it, and it will behave differently depending on his type.
#多态和方法

From randomImport Choice
x = Choice ([' Hello world ', [' 1 ',' 1 ',' 1 ',' 2 ',' 3 '])
Print (x)
Print (X.count (' 1 '))#1出现的次数 do not need to detect the type just need to know conut this method
#多态的多种形式: + operations function on strings, numbers

#2 encapsulation hides excess information from other areas in the global scope
#3 inheritance: Do not want code to reuse the original code
#4 class
#创建类
_metaclass_=Type
Class Person:
Def setname (Self,name):
Self.name = Name
Def getname (Self):
ReturnSelf.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)
#-------------------------Output----------------------------------#
"""
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
"""

#特性, Functions, methods
Class class:
Def method (Self):
Print"I am Self")
Def fuction ():
Print"I don ' t ...")

obj = Class ()
Obj.method ()
Obj.method = fuction# attribute is bound to a normal function
Obj.method ()

Test = Obj.method#test变量引用绑定方法上
Test ()

#-------------------------Output----------------------------------#
"""
I am Self
I don ' t ...
I don ' t.
"""

#私有特性: To make the feature and method private (outside inaccessible), simply double-underline the name
#指定超类
Class Filter:
DEF init (Self):
Self.blocked=[]
DEF filter (Self,test):
return [xFor XIn testIf XNot inSelf.blocked]
Def _test (Self):
Print"I am Private")
Class Childfilter (Filter):#指定超类 Childfilter as a subclass of filter
DEF init (Self):
Print"I am the subclass is overriding the parent class method")
self.blocked=[' As ']
f = Filter ()
F.init ()
Print (F.filter ([1,2,3]))

F1 = Childfilter ()
F1.init ()
Print (F1.filter ([1,23,56]))

#-------------------------Output----------------------------------#
"""
C:\python3.7\python.exe d:/python-test/qiubai/qiubai/test6.py
[1, 2, 3]
I'm a subclass. Overriding the parent class method
[1, 23, 56]
"""


#捕获异常
Try
x =5
y =0
Print (x/y)
ExceptZerodivisionerror:
Print"Denominator cannot be 0")
#-------------------------Output----------------------------------#
"""
C:\python3.7\python.exe d:/python-test/qiubai/qiubai/test6.py
The denominator cannot be 0
"""

# Raise
Class Muffledcalculator:
muffed =False
Def Calc (SELF,EXPR):
Try
Returneval (expr)
ExceptZerodivisionerror:
IfSelf.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 '))
#-------------------------Output----------------------------------#
"""
C:\python3.7\python.exe d:/python-test/qiubai/qiubai/test6.py
The denominator cannot be 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)
ExceptZerodivisionerror,TypeError,Nameerror). E:
Print"Your Num were Bug")
Print (e)


While True:
Try
x =intInput"Input your first num:"))
y=intInput"Input YOUR second num:"))
Value = x/y
Print (value)
ExceptEXCEPTION.E:
Print"Exception", E)
Print"Try Again")
Else
Break


"""
#-------------------------Output----------------------------------#
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/qiuba i/test6.py ", line 145, in <module> value = X/yzerodivisionerror:division by zeroduring handling of the above except Ion, another exception Occurred:traceback (most recent): File ' d:/python-test/qiubai/qiubai/test6.py ', line 147 , in <module> except Exception.e:attributeerror:type object ' Exception ' have 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 A Gain ") Else: #只有程序没有异常情况才会退出 Whenever an error occurs, the program constantly re-asks for the input break" "" #------------------------- Output----------------------------------#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 #程序崩溃之前 For x variable cleanup "" "C:\python3.7\python.exe d:/python-test/qiubai/qiubai/test6.pyclean up .... Traceback (most recent): File "d:/python-test/qiubai/qiubai/test6.py", line 203, in <module> x = X/0type error:unsupported operand type (s) for/: ' Nonetype ' and ' int ' "" "

Python abstraction and exception handling

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.