- Exception handling
- Object oriented
- Iterators and generators
Python Exception handling
- The following code triggers a filenotfounderror
>>> Open ("Notexist.txt") Traceback (most recent call last): File "<stdin>", line 1, in <module> Filenotfounderror: [Errno 2] No such file or directory: ' Notexist.txt '
>>> Raise Filenotfounderror
- Catching exceptions using Try,except,finally,else
Try: open (r "C:\Users\kingsoft\Desktop\notexist.txt") except Filenotfounderror as E: print ("File not exist ... ") except (name1,name2): print (" IO error is true ... ") Else: print (" file exist.. ") Finally: print ("Always do ...")
Python Object-oriented
Python is completely object-oriented, and everything in Python is an object, including variables, functions, and so on.
Class MyException ():p
Class person ():d EF __init__ (Self, name): Self.name = Namedef sayname (self):p rint Self.namem = person ("Joe") print ( M.sayname ())
- Examples of district classifications and classes
Class person ():d EF __init__ (Self, name): Self.name = Nameperson.name = Namedef sayname (self):p rint ("MyName is:" + Self.nam e) Print ("Myexceptionname is:" + person.name) def changeothername (self, name):P erson.name = Namedef __del__ (self):p rint ( Self.name + "is Gone") m = Person ("Joe") M.sayname () print ("M.name:" + m.name) m.test= "TT" Print (m.test) j = Person ("Jason") J . Sayname () j.changeothername (j.name) m.sayname ()
- Class inheritance, polymorphism, and encapsulation concepts
Generators and iterators
- The _iter_ method returns an iterator that refers to an object with the next method
Class Fibs (object): "" "DocString for Fibs" "" "Def __init__ (Self, max): Self.max = MAXSELF.A = 0self.b = 1def __next__ (self): fi b = Self.aif fib > self.max:raise stopiterationself.a, self.b = self.b, SELF.A + Self.breturn fib# return iterator def __iter__ (sel f): Return SELFFIB = Fibs (+) for F in Fib:print (F, end= "")
- Object Iterable and iterators can be iterated iterator
- Generator, the generator quickly generates iterators through yield statements, making the function a generator
#斐波那契数列def getfibs (max): a = 0b = 1while A < Max:a, b= b, a+bvalue = Ayield Valueprint (getfibs (+)) for I in Getfibs (10 XX):p rint (i)
- Simple Understanding Generator
Def gen (): Yield "Hello" yield "how" yield "is" yield "you" for I in Gen ():p rint (i)
Python Basics-exceptions, objects, and iterators