Property management functions for objects:
getattr (obj, Name[,default)
Gets the properties of the object from the object, GetAttr (x, "Y") equals x, y when the property
does not exist when the default parameter is given returns the default
If default is not given, a attributeerror error is generated
hasattr(obj, name) returns the object with the given name if obj has this property
This approach avoids throwing an error at getattr(obj,name)
SetAttr (obj, name, value) to object obj named name.
property to set the corresponding value , set (x, ' Y ', v) equal to x.y = V
delattr (obj, name) Delete the name property in the object obj
, Delattr (x, ' Y ') is equivalent to Del x.y
Example:
Class Dog: PASSD = Dog () D.color = "White" v = getattr (d, "color") # equals v = D.colorv = GetAttr (d, "kinds") # Error, no D.kinds Property V = getattr (d, "kinds", "without this attribute") # v= ' Without this attribute ' hasattr (d, ' color ') # truehasattr (d, ' kinds ') # Falsesetattr (d, ' kinds ', ' boe ') # equals d.kinds = ' boe ' hasattr (d, ' kinds ') # truedelattr (d, ' kinds ') # equals del D.kindshasattr (d, ' kinds ') # False
Exception (Advanced):
Statements that can be used for exceptions
try-except # catching exceptions , getting notified
try-finally # Left any process (normal/exception) must execute the statement to be executed
Raise # send Exception
assert # send exception notification based on condition
With statement:
Syntax :
With expression 1[as variable 1], expression 2[as variable 2] ....
function :
Use and access to resources to ensure that the use of the process regardless of
whether an exception occurs will perform the necessary cleanup operationsand release the resource
(e.g., automatic closing of files after use, automatic acquisition and release of locks in threads, etc.)
Description :
Execution expression, the object generated by the variable binding in the AS clause
The WITH statement does not change the state of the exception
Example:
# with statement open file and auto close try: With open ("A.txt") as F: for X in F: print (x) int ("abc") # exception except OSError : Print ("File open failed") except ValueError: print ("Error during file operation") # try-finally statement Open file and close try: f = open ("A.txt") For x in F: print (x) except OSError: print ("Open file failed") except ValueError: print ("Error during file operation") finally: F.close ()
# Modify the original copy file function Src_filename = input ("Enter source file path name:") Dst_filename = input (' Enter destination file pathname: ') Try: With open (src_filename , ' RB ') as SRC, open (Dst_filename, ' WB ') as DST: # Open source file to read data while True: b = src.read (4096) if Not B: # I can't read the data anymore break Dst.write (b) print ("Copy succeeded") except OSError: print ("Copy failed")
Environment Manager:
Classes with __enter__ and __exit__ instance methods within a class are called environment Managers
The object that can be managed with is the environment manager
Description
__ENTER__ will be called when entering the WITH statement and return the object bound by the as variable
The __exit__ will be called when it leaves the WITH statement and can be used to determine
whether an exception occurred while leaving the With statement and handled accordingly
Example:
# A custom class creates an object that can use the WITH statement Class A: "" The object of this class can be used with the WITH statement to manage ' def __enter__ (self): print ("has entered the With statement, Resource allocation succeeded ") return self # <<<--The object returned here will be bound by the as variable def __exit__ (self, exc_type, Exc_val, EXC_TB): Print ("Leave with statement, resource freed successfully") if Exc_type is none: print ("No exception when leaving with statement") else: print ("Exception type with exception occurred:", Exc_type, "outlier:", Exc_val) with a () as a: print ("This is the statement in the With statement") raise ValueError ("intentionally created exception")
Operator Overloading:
What is operator overloading
Enable custom class-generated objects (instances) to operate with operators
Role:
1. Allow instances of a custom class to run operator operations
2. Make the program simple and easy to read
3. assigning operators to new arithmetic rules for defining objects
Description
The parameters of an operator overloaded method already have a fixed meaning and are not recommended to change the original meaning
Arithmetic operator overloading:
Method name operators and expression descriptions
__add__ (self, RHS) Self + rsh addition
__sub__ (self, RHS) Self-rsh subtraction
__mul__ (self, RHS) self * rsh multiplication
__truediv__ (self, RHS) Self/rsh Division
__floordiv__ (self, RHS) Self//rsh floor except
__mod__ (self, RHS) Self% rsh model
__pow__ (self, RHS) self * * RSH power
RHS (self hand side) right hand side
Example:
Class MyNumber: def __init__ (Self, val): self.data = val def __repr__ (self): return "%d"% self.data def __add__ (self, rsh): v = self.data + rsh.data return MyNumber (v) def __sub__ (self, rsh): return MyNumber (self.data-rsh.data) n1 = MyNumber (+) N2 = MyNumber ($) n3 = n1 + n2 # equals n3 = N1.__add__ (n2) # n3 = N1.__a Dd__ (n2) print (t (N1, "-", N2, "=", n1-n2)
Overloading of inverse arithmetic operators
an typeerror error occurs when the left side of the operator is a built-in type, and the right-hand object for a custom type is arithmetic operator operation.
Operator overloading is implemented because the code for the built- in class cannot be modified , and reverse arithmetic operator overloading is required
Inverse arithmetic operator overloading
Method name operators and expression descriptions
__radd__ (self, LHS) LHS + self Addition
__rsub__ (self, LHS) lhs-self subtraction
__rmul__ (self, LHS) LHS * Self multiplication
__rtruediv__ (self, LHS) Lhs/self Division
__rfloordiv__ (self, LHS) LHS//self floor except
__rmod__ (self, LHS) lhs% self modulo (redundancy)
__rpow__ (self, LHS) LHS * * Self power
LHS (left hand side) right hand side
Example:
# This example shows the overloaded class MyList: def __init__ (self, lst=[]): "" Creates a Bata property for each object within the initialization method Bata Used to bind each object's own list "' Self.beta = [x for x in LST] # self.bata = List (LST) def __repr__ (self): return '%s ' "% Self.beta def __mul__ (self, RHS): return MyList (Self.beta * rhs) print (" __mul__ is called ") def __rmul __ (self, LHS): print ("__rmul__ is called") return MyList (Self.beta * lhs) # reverse parameter L1 = MyList ([1, 2, 3]) L2 = Mylis T (range (4, 7)) L3 = 2 * L1 # l1.__rmul__ (2) print (L3) L5 = L1 * 2 # L5 = l1.__mul__ (2) print (L5) # MyList ([1, 2 , 3, 1, 2, 3])
Overloading of compound assignment arithmetic operators
Take the compound assignment arithmetic operator x + = y As an example, this operation takes precedence on calling the X.__iadd__ (Y) method ,
If there is no __iadd__ method, the compound assignment operation is disassembled to x = x + y, and then the x = x.__add__ (y) method is called
TypeError Exception is triggered if the __add__ method is no longer present
Other compound assignment operators also have the same rules
Compound assignment arithmetic operator overloading
Method name operators and expression descriptions
__iadd__ (self, LHS) LHS + = self addition
__isub__ (self, LHS) lhs-= self subtraction
__imul__ (self, LHS) lhs *= self multiplication
__itruediv__ (SELF,LHS) LHS/= Self Division
__ifloordiv__ (self, LHS) LHS//= self floor except
__imod__ (self, LHS) lhs%= self modulo (redundancy)
__ipow__ (self, LHS) LHS **= Power
Example:
Class MyList: def __init__ (self, lst=[]): "" Creates a Bata property for each object within the initialization method bata the list "'" to bind each object's own Self.beta = [x for x on LST] self.bata = list (LST) def __repr__ (self): return '%s '% Self.beta def __iadd_ _ (Self, RHS): Self.beta + = Rhs.beta # ID unchanged return self def __add__ (self, RHS): return MyList ( Self.beta + Rhs.beta) # ID will not change L = MyList ([1, 2, 3]) def F1 (LST): lst + = MyList ([4, 5, 6]) F1 (L) print (L)
Compound assignment arithmetic operator overloading
Method name operators and expression descriptions
__lt__ (self, RHS) Self < RHS less than
__le__ (self, RHS) The self <= RHS is less than or equal to
__gt__ (self, RHS) self > RHS greater than
__ge__ (self, RHS) The self >= RHS is greater than or equal to
__eq__ (self, rhs) self = = RHS equals
__ne__ (self, rhs) self! = RHS Not equal to
Example:
# This example shows the overload of the comparison operator class MyList: def __init__ (self, iterable): self.data = List (iterable) def __repr__ (self): return ' MyList (%s) '% Self.data def __eq__ (self, RHS): return self.data = = Rhs.data def __gt__ (self, RHS): return self.data > Rhs.datal1 = MyList ([1, 2, 3]) L2 = MyList ([1, 2, 3]) print (L1 = L2) # trueprint (L1 ; L2) # false# print (L1 = = L2) # If there is no __eq__ method to determine the two objects id# print (L1 > L2) # If there is no __gt__ method error
Bitwise operator Overloading
Method name operators and expression descriptions
__invert__ (self)-self-inverse (unary operator)
__and__ (self, RHS) Self & RHS bit with
__or__ (self, RHS) self | RHS bit or
__xor__ (self, RHS) self ^ RHS bit xor
__lshift__ (self, RHS) Self << RHS shift left
__rshift__ (self, RHS) Self >> RHS right shift
Reverse bitwise operator Overloading
Method name operators and expression descriptions
__rand__ (self, LHS) LHS & self bit with
__ror__ (self, LHS) LHS | Self bit or
__rxor__ (self, LHS) lhs ^ The self bit XOR
__rlshift__ (self, LHS) LHS << left shift
__rrshift__ (self, LHS) LHS >> self Move Right
Compound Assignment bitwise operator overloading
Method name operators and expression descriptions
__iand__ (self, RHS) The self &= RHS bit and
__ior__ (self, RHS) self |= RHS bit or
__ixor__ (self, RHS) The self ^= RHS bit XOR
__ilshift__ (self, RHS) Self <<= RHS left shift
__irshift__ (self, RHS) Self >>= RHS right shift
Unary operator overloading
Method name operators and expression descriptions
__invert__ (self)-self-inverse (unary operator)
__pos__ (self) + self Plus
__neg__ (self)-self minus
Grammar:
def __xxx__ (self):
Example:
# This example shows the overloading of the unary operator class MyList: def __init__ (self, lst=[]): "" Creates a Bata property for each object within the initialization method bata the list to bind each object's own c3/> " Self.beta = [x for x in LST] # self.bata = List (LST) def __repr__ (self): return '%s '% self.beta
def __neg__ (self): return MyList ((x-for-Self.beta) def __pos__ (self): return MyList ((ABS (x) for X in Self.beta)) # L = [] # for X in Self.beta: # if x > 0: # L.append (x) # Els E: # L.append (-X) # return MyList (L) L1 = MyList ([1,-2, 3, -4, 5]) L2 =-l1print (L2) # MyList ([-1, 2,- 3, 4, 5]) # Implements a custom list with the plus sign operator that returns all elements as positive numbers L3 = + l1print (L3) # MyList ([1, 2, 3, 4, 5])
In/not in operator overloading
Overloaded methods:
def __contains__ (self, E):
....
Example:
# in no in overloaded class MyList: def __init__ (self, lst=[]): "" Creates a Bata property for each object within the initialization method Bata to bind each object's own list "' Self.beta = [x for x in LST] # self.bata = List (LST) def __repr__ (self): return '%s '% self.beta< C10/>def __contains__ (Self, e): return e in self.betal1 = MyList ([1, 2, -3, 4,-5]) print (2 in L1) print (3 in L1) print ( 4 in L1) print (5 in L1)
Overloading of index and slice operators
Method name operators and expression descriptions
__getitem__ (self, i) x = self[i] Index/Slice value
__setitem__ (self, I, val) self[i] = Val Index/slice Assignment
__delitem__ (self, i) del self[i] Delete index/slice
Role:
Enables objects of a custom class to support indexing and slicing operations
Example:
# This example shows the overloaded class MyList for the index/slice operator: def __init__ (self, iterable): self.data = List (iterable) def __repr__ ( Self): return ' MyList (%s) '% Self.data def __getitem__ (self, i): print ("The value of index i is:", i) return self.data [I] def __setitem__ (self, I, v): print ("__setitem__ called, i=", I, ' v= ', v) self.data[i] = v def __delitem__ (self, i): del self.data[i]l1 = MyList ([1,-2, 3, -4, 5]) v = l1[2] # v = 3print (v) # 3l1[1] = 2print (L1) # My List ([1, 2, 3, -4, 5]) del l1[3]print (L1) # MyList ([1, 2, 3, 5])
Slice function:
Role:
Used to create a slice tile object that stores information about the slice
Format:
Slice (Start=none, Stop=none, Step=none)
Slice properties of an object
The starting value of the S.start slice, which defaults to none
S.stop the end value of the slice, default to None
S.step slice step, default to None
Example:
# This example shows the overloaded class MyList for the index/slice operator: def __init__ (self, iterable): self.data = List (iterable) def __repr__ ( Self): return ' MyList (%s) '% Self.data def __getitem__ (self, i): print ("The value of index i is:", i) if the type (i) is int: Print ("Indexing operation") elif type (i) is slice: print ( "slicing operation") print (" starting value is:", I.start) print (" The terminating value is: ", i.stop) print (" Step value is: ", I.step) return self.data[i] def __setitem__ (self, I, v): Print (" _ _setitem__ called, i= ", I, ' v= ', v) self.data[i] = v def __delitem__ (self, i): del self.data[i]l1 = MyList ([1, -2, 3, -4, 5]) L2 = L1[::2]print (L2)
Attribute Properties @property
Implements the getter and setter functions that are owned by other languages
Role:
Used to simulate a property
The value and assignment of the simulated attribute can be controlled by the @property adorner
For example, see:
Example:
Class Student: def __init__ (self, s): Self.__score = s # private attribute, do not let others arbitrarily modify the score @property def score ( Self): " camouflage simulates a private performance attribute and returns the score" ' Return self.__score @score. Setter def score (self, v): "' Implement setter Setters, limit the user's copy to " assert 0 <= v <= 100", "Invalid result" Self.__score = vs = Student (+) print (S.score)
# want to have a property to get results The virtual attribute cannot be copied s.score = # by S.score to modify the score print (S.score) # Modify Success S.score It looks like the property is an impersonation attribute the actual interior has been replaced
Problem:
L = [1, 2, 3]
def f1 (LST):
LST + = [4, 5, 6]
F1 (L)
Print (L) # [1, 2, 3, 4, 5, 6] Why
L = (1, 2, 3)
def f1 (LST):
LST + = (4, 5, 6) # LST = lst + (4, 5, 6)
F1 (L)
Print (L) # (1, 2, 3) why
Practice:
1. Implement two custom list additions
Class MyList:
.... Implement it yourself here
L1 = MyList ([1, 2, 3])
L2 = MyList (Range (4, 7))
L3 = L1 + L2
Print (L3) # MyList ([1, 2, 3, 4, 5, 6])
L4 = L2 + L1
Print (L4) # MyList ([4, 5, 6, 1, 2, 3])
L5 = L1 * 2
Print (L5) # MyList ([1, 2, 3, 1, 2, 3])
Practice:
The realization of an ordered set class Orderset () can realize the intersection of two sets &
Complement set-symmetric complement ^, ==/!=, in/not in, etc.
Requires the collection to be stored internally with list
Class Orderset:
...
S1 = Orderset ([1, 2, 3, 4])
S2 = Orderset ([3, 4, 5])
Print (S1 & S2) # Orderset ([3, 4])
Print (S1 | s2) # orderset ([1, 2, 3, 4, 5])
Print (s1 ^ s2) # Orderset ([1, 2, 5])
If Orderset ([1, 2, 3])! = Orderset ([3, 4, 5]):
Print ("unequal")
If S2 = = Orderset (3, 4, 5):
Print (' S2 = = Orderset (3, 4, 5) is True ')
If 2 in S1:
Print ("2 in S1")
Python full stack engineer (0 basics to Mastery) Tutorial 29th (Exception (advanced), operator overloading)