current position:Home>Advanced Python Basics: from functions to advanced magic methods

Advanced Python Basics: from functions to advanced magic methods

2022-01-30 15:36:45 chaoyu

function

Definition of function

  • Function to def Key words start with , Followed by the function name and parentheses ().
  • The code executed by the function starts with a colon , And indent .
  • return [ expression ] End function , Optionally return a value to the caller . Without expression return It's equivalent to returning to None

grammar

def functionname (parameters):
       " Function document string "
        functionsuite
        return [expression]
 Copy code 

Function call

def printme(str):
    print(str)


printme(" I'm going to call user defined functions !")  #  I'm going to call user defined functions !
printme(" Call the same function again ")  #  Call the same function again 
temp = printme('hello') # hello
print(temp)  # None
 Copy code 

Function documentation

def MyFirstFunction(name):
    " In the process of function definition name It's a parameter "
    #  because Ta It's just a form , Indicates that it occupies a parameter position 
    print(' Passed in {0} It's called an argument , because Ta Is the specific parameter value !'.format(name))


MyFirstFunction(' Old horse's procedural life ')  
#  The program life of the old horse passed in is called an argument , because Ta Is the specific parameter value !

print(MyFirstFunction.__doc__)  
#  In the process of function definition name It's a parameter 

help(MyFirstFunction)
# Help on function MyFirstFunction in module __main__:
# MyFirstFunction(name)
#  In the process of function definition name It's a parameter 
 Copy code 

Function parameter

  1. Positional arguments (positional argument)
def functionname(arg1):
       " Function document string "
       functionsuite
       return [expression]
 Copy code 
  • arg1 - Positional arguments , These parameters are calling the function (call function) The position should be fixed
  1. Default parameters (default argument)
def functionname(arg1, arg2=v):
       " Function document string "
       functionsuite
       return [expression]
 Copy code 
  • arg2 = v - Default parameters = The default value is , When you call a function , If the value of the default parameter is not passed in , Is considered the default value .
  • The default parameter must be placed in the position parameter Back , Otherwise, the program will report an error .
  • Python The order of the parameters when the function is allowed to be called is not the same as when it is declared , because Python The interpreter can match parameter values with parameter names
  1. Variable parameters (variable argument)
def functionname(arg1, arg2=v, *args):
       " Function document string "
       functionsuite
       return [expression]
 Copy code 
  • *args - Variable parameters , It can be from zero to any , Automatically assemble into metagroups .
  • With an asterisk (*) The variable name of will hold all unnamed variable parameters
  1. Key parameters (keyword argument)
def functionname(arg1, arg2=v, args, *kw):
       " Function document string "
       functionsuite
       return [expression]
 Copy code 
  • **kw - Key parameters , It can be from zero to any , Automatically assembled into a dictionary

「 Variable parameters 」 and 「 Key parameters 」 The similarities and differences of are summarized as follows :

  • Variable parameters allow zero to any number of parameters to be passed in , They are automatically assembled into a tuple when a function is called (tuple).
  • Keyword parameters allow zero to any number of parameters to be passed in , They are automatically assembled into a dictionary inside the function (dict)
  1. Named key parameters (name keyword argument)
def functionname(arg1, arg2=v, args, *, nkw, *kw):
       " Function document string "
       functionsuite
       return [expression]
 Copy code 
  • *, nkw - Named key parameters , The keyword parameter that the user wants to enter , The way to define it is in nkw Put a separator in front of it *
  • If you want to restrict the name of a keyword parameter , You can use it 「 Named key parameters 」
  • When using named keyword parameters , Special attention should be paid to not missing the parameter name
  • No parameter name written nwk, therefore 10 Be treated as 「 Positional arguments 」, The original function has only 1 A position function , Now call 2 individual , So the program will report an error
  1. Parameter combination

stay Python Define function in , You can use the position parameter 、 Default parameters 、 Variable parameters 、 Name keyword parameters and keyword parameters , this 5 In two parameters 4 All can be used together , But notice , The order of parameter definitions must be :

  • Positional arguments 、 Default parameters 、 Variable and key parameters .
  • Positional arguments 、 Default parameters 、 Name keyword parameters and keyword parameters .

Pay attention to the syntax of defining variable parameters and keyword parameters :

  • *args It's a variable parameter ,args It received a tuple
  • **kw It's a keyword parameter ,kw It received a dict

Keyword parameters are named to limit the parameter names that callers can pass in , You can also provide default values . Don't forget to write the separator when defining named keyword parameters *, Otherwise, it's a positional parameter .

Warning : Although it can be combined as much as 5 Parameters , But don't use too many combinations at the same time , Otherwise, the function is hard to understand

The return value of the function

def add(a, b):
    return a + b
print(add(1, 2))  # 3
print(add([1, 2, 3], [4, 5, 6]))  # [1, 2, 3, 4, 5, 6]

#  example 2
def back():
    return [1, ' Pony's procedural life ', 3.14]
print(back())  # [1, ' Pony's procedural life ', 3.14]

#  example 3
def back():
    return 1, ' Pony's procedural life ', 3.14
print(back())  # (1, ' Pony's procedural life ', 3.14)

#  example 4
def printme(str):
    print(str)
temp = printme('hello') # hello
print(temp) # None
print(type(temp))  # <class 'NoneType'>
 Copy code 

Variable scope

  • Python in , Program variables are not accessible anywhere , Access depends on where the variable is assigned .
  • Variables defined within a function have local scope , This variable is called a local variable .
  • Variables defined outside a function have global scope , This variable is called a global variable .
  • Local variables can only be accessed inside the function they are declared , Global variables can be accessed throughout the program
  • When the internal scope wants to modify the variables of the external scope , You use global and nonlocal Keyword.
num = 1
def fun1():
    global num  #  Need to use  global  Keyword declaration 
    print(num)  # 1
    num = 123
    print(num)  # 123
fun1()
print(num)  # 123
 Copy code 

Nested Function

def outer():
    print('outer The function is called here ')
    def inner():
        print('inner The function is called here ')
    inner()  #  This function can only be used in outer The function is called internally 
outer()
# outer The function is called here 
# inner The function is called here 
 Copy code 

Closure

  • Is an important syntax structure of functional programming , Is a special embedded function
  • If you reference an external non global variable in an internal function , So internal functions are considered closures
  • Through closures, you can access variables in outer non global scope , This scope is called Closure scope
def funX(x):
    def funY(y):
        return x * y

    return funY


i = funX(8)
print(type(i))  # <class 'function'>
print(i(5))  # 40
 Copy code 
  • If you want to modify variables in the closure scope, you need nonlocal keyword
def outer():
    num = 10
    def inner():
        nonlocal num  # nonlocal Keyword declaration 
        num = 100
        print(num)
    inner()
    print(num)
outer()

# 100
# 100
 Copy code 

recursive

  • If a function calls itself internally , This function is a recursive function

Factorial n! = 1 x 2 x 3 x ... x n

#  Utilization cycle 
n = 5
for k in range(1, 5):
    n = n * k
print(n)  # 120

#  Recursion 
def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)
print(factorial(5)) # 120
 Copy code 

Fibonacci sequence

#  Utilization cycle 
i = 0
j = 1
lst = list([i, j])
for k in range(2, 11):
    k = i + j
    lst.append(k)
    i = j
    j = k
print(lst)  
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

#  Recursion 
def recur_fibo(n):
    if n <= 1:
        return n
    return recur_fibo(n - 1) + recur_fibo(n - 2)
lst = list()
for k in range(11):
    lst.append(recur_fibo(k))
print(lst)  
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
 Copy code 
  • Set the number of layers of recursion ,Python The default number of recursion layers is 100
import sys
sys.setrecursionlimit(1000)
 Copy code 

Lambda- expression

Definition of anonymous function

stay Python There are two kinds of functions in :

  1. use def Keyword defined normal function
  2. use lambda Keyword defined anonymous functions

Python Use lambda Keywords to create anonymous functions , Instead of def key word , It has no function name , The syntax is as follows :

lambda argument_list: expression
 Copy code 
  • lambda - Define keywords for anonymous functions .
  • argument_list - Function parameter , They can be positional parameters 、 Default parameters 、 Key parameters , It's the same as the parameter type in a normal function .
  • :- The colon , Add a colon between the function parameter and the expression .
  • expression - It's just an expression , Enter function parameters , Output some values

Be careful :

  • expression There is no return sentence , because lambda You don't need it to return , The result of the expression itself is the return value .
  • Anonymous functions have their own namespace , And can't access parameters outside their parameter list or in the global namespace

Application of anonymous function

Functional programming Every piece of code is immutable , They are all in the form of pure functions . Pure functions here , It means that functions are independent of each other 、 They don't influence each other , For the same input , There will always be the same output , There are no side effects

#  Non functional programming 
def f(x):
    for i in range(0, len(x)):
        x[i] += 10
    return x
x = [1, 2, 3]
f(x)
print(x)
# [11, 12, 13]

#  Functional programming 
def f(x):
    y = []
    for item in x:
        y.append(item + 10)
    return y
x = [1, 2, 3]
f(x)
print(x)
# [1, 2, 3]
 Copy code 

Anonymous functions Higher order functions often used in functional programming (high-order function) in , There are two main forms :

  1. Parameter is a function (filter, map)
  2. The return value is a function (closure)

Such as , stay filter and map Applications in functions :

  • filter(function, iterable) Filter sequence , Filter out the elements that do not meet the conditions , Returns an iterator object , If you want to convert to a list , have access to list() To convert
odd = lambda x: x % 2 == 1
templist = filter(odd, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(templist))  # [1, 3, 5, 7, 9]
 Copy code 
  • map(function, *iterables) Map the specified sequence according to the function provided
m1 = map(lambda x: x ** 2, [1, 2, 3, 4, 5])
print(list(m1))  
# [1, 4, 9, 16, 25]
m2 = map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
print(list(m2))  
# [3, 7, 11, 15, 19]
 Copy code 
  • except Python These built-in functions , We can also define higher-order functions ourselves
def apply_to_list(fun, some_list):
    return fun(some_list)

lst = [1, 2, 3, 4, 5]
print(apply_to_list(sum, lst))
# 15

print(apply_to_list(len, lst))
# 5

print(apply_to_list(lambda x: sum(x) / len(x), lst))
# 3.0
 Copy code 

Classes and objects

Properties and methods constitute objects

  • object = attribute + Method

Object is an instance of a class . let me put it another way , Class mainly defines the structure of the object , Then we create objects using classes as templates . Class contains not only method definitions , It also contains data shared by all instances .

  • encapsulation : Information Hiding Technology

Keywords can be used class Definition Python class , Keyword followed by the name of the class 、 Semicolons and class implementations

  • Inherit : A mechanism for subclasses to automatically share data and methods between parent classes
  • polymorphic : Different objects respond to different actions for the same method

self What is it? ?

Python Of self amount to C++ Of this The pointer

class Test:
    def prt(self):
        print(self)
        print(self.__class__)


t = Test()
t.prt()
# <__main__.Test object at 0x000000BC5A351208>
# <class '__main__.Test'>
 Copy code 

There is only one special difference between a class method and a normal function —— They must have an additional first parameter name ( Corresponding to this instance , That is, the object itself ), By convention its name is self. When a method is called , We don't need to explicitly provide parameters self The corresponding parameters

Python The magic method of

  • Class has a name __init__(self[, param1, param2...]) The magic method of , This method is called automatically when the class is instantiated
class Ball:
    def __init__(self, name):
        self.name = name

    def kick(self):
        print(" My name is %s, blamed , Who kicked me ..." % self.name)

a = Ball(" The ball A")
b = Ball(" The ball B")
c = Ball(" The ball C")
a.kick()
#  My name is ball A, blamed , Who kicked me ...
b.kick()
#  My name is ball B, blamed , Who kicked me ...
 Copy code 

Public and private

To define a private variable, you only need to add... Before the variable name or function name “__” Two underscores , Then the function or variable will be private

  • Class
class JustCounter:
    __secretCount = 0  #  Private variables 
    publicCount = 0  #  Open variables 

    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print(self.__secretCount)

counter = JustCounter()
counter.count()  # 1
counter.count()  # 2
print(counter.publicCount)  # 2

# Python Private is pseudo private 
print(counter._JustCounter__secretCount)  # 2 
print(counter.__secretCount)  
# AttributeError: 'JustCounter' object has no attribute '__secretCount'
 Copy code 
  • Class
class Site:
    def __init__(self, name, url):
        self.name = name  # public
        self.__url = url  # private

    def who(self):
        print('name : ', self.name)
        print('url : ', self.__url)

    def __foo(self):  #  Private method 
        print(' This is the private method ')

    def foo(self):  #  Public methods 
        print(' It's the public way ')
        self.__foo()


x = Site(' Old horse's procedural life ', 'https://blog.csdn.net/LSGO_MYP')
x.who()
# name :  Old horse's procedural life 
# url : https://blog.csdn.net/LSGO_MYP

x.foo()
#  It's the public way 
#  This is the private method 

x.__foo()
# AttributeError: 'Site' object has no attribute '__foo'
 Copy code 

Inherit

Definition of derived class

class DerivedClassName(BaseClassName):
       statement-1
              .
              .
              .
       statement-N
 Copy code 

BaseClassName( Base class name ) Must be in the same scope as the derived class definition . Except class , You can also use expressions , This is useful when the base class is defined in another module

class DerivedClassName(modname.BaseClassName):
       statement-1
              .
              .
              .
       statement-N
 Copy code 

example : If a method or property with the same name as the parent class is defined in the subclass , The method or property corresponding to the parent class will be automatically overridden

#  Class definition 
class people:
    #  Define basic attributes 
    name = ''
    age = 0
    #  Define private properties , Private properties cannot be accessed directly outside the class 
    __weight = 0

    #  Define construction method 
    def __init__(self, n, a, w):
        self.name = n
        self.age = a
        self.__weight = w

    def speak(self):
        print("%s  say :  I  %d  year ." % (self.name, self.age))


#  Single inheritance example 
class student(people):
    grade = ''

    def __init__(self, n, a, w, g):
        #  Call the constructor of the parent class 
        people.__init__(self, n, a, w)
        self.grade = g

    #  Override method of parent class 
    def speak(self):
        print("%s  say :  I  %d  Year old , I'm reading  %d  grade " % (self.name, self.age, self.grade))


s = student(' Pony's procedural life ', 10, 60, 3)
s.speak()
#  Pony's procedural life   say :  I  10  Year old , I'm reading  3  grade 
 Copy code 

If the above procedure removes :people.__init__(self, n, a, w), The output : say : I 0 Year old , I'm reading 3 grade , Because the constructor of the child class overrides the constructor of the parent class

Python Although it supports the form of multiple inheritance , But we generally don't use multiple inheritance , Because it's easy to cause confusion

Combine

class Turtle:
    def __init__(self, x):
        self.num = x


class Fish:
    def __init__(self, x):
        self.num = x


class Pool:
    def __init__(self, x, y):
        self.turtle = Turtle(x)
        self.fish = Fish(y)

    def print_num(self):
        print(" There are turtles in the pool %s only , Little fish %s strip " % (self.turtle.num, self.fish.num))


p = Pool(2, 3)
p.print_num()
#  There are turtles in the pool 2 only , Little fish 3 strip 
 Copy code 

class 、 Class objects and instance objects

Class object : Create a class , In fact, it is also an object that opens up a space in memory , Called class objects , There is only one class object .

class A(object):
       pass
 Copy code 

Instance object : Objects created by instantiating classes , It's called an instance object , Instance objects can have more than one

  • Class properties : Variables defined outside methods in a class are called class properties . Class attributes belong to class objects, and multiple instance objects share the same class attribute , To put it bluntly, it means that all objects instantiated by the class can be shared .
class A():
    a = 0  # Class properties 
    def __init__(self, xx):
        A.a = xx  # Using class properties, you can use  ( Class name . Class properties ) call .
 Copy code 
  • Instance attributes : Instance properties are related to a specific instance object , And one instance object and another instance object do not share properties , To be clear, instance properties can only be used in your own objects , Other objects cannot be used directly , because self Who is calling , Its value belongs to the object
#  create a class object 
class Test(object):
    class_attr = 100  #  Class properties 

    def __init__(self):
        self.sl_attr = 100  #  Instance attributes 

    def func(self):
        print(' Class object . The value of the class property :', Test.class_attr)  #  Calling class properties 
        print('self. The value of the class property ', self.class_attr)  #  It is equivalent to putting the class attribute   Become instance properties 
        print('self. The value of the instance property ', self.sl_attr)  #  Invoke instance properties 


a = Test()
a.func()

#  Class object . The value of the class property : 100
# self. The value of the class property  100
# self. The value of the instance property  100

b = Test()
b.func()

#  Class object . The value of the class property : 100
# self. The value of the class property  100
# self. The value of the instance property  100

a.class_attr = 200
a.sl_attr = 200
a.func()

#  Class object . The value of the class property : 100
# self. The value of the class property  200
# self. The value of the instance property  200

b.func()

#  Class object . The value of the class property : 100
# self. The value of the class property  100
# self. The value of the instance property  100

Test.class_attr = 300
a.func()

#  Class object . The value of the class property : 300
# self. The value of the class property  200
# self. The value of the instance property  200

b.func()
#  Class object . The value of the class property : 300
# self. The value of the class property  300
# self. The value of the instance property  100
 Copy code 

Property is the same as the method name , Property will override the method

What is binding ?

Python It is strictly required that the method needs to have an instance to be called , This limitation is actually Python The so-called binding concept .

Python The data properties of an object are usually stored in a file named .__ dict__ In the dictionary , We have direct access __dict__, Or use Python Built in functions for vars() obtain .__ dict__

Some related built-in functions (BIF)

  • issubclass(class, classinfo) Method is used to judge the parameters class Whether it is a type parameter classinfo Subclasses of .
  • A class is considered a subclass of itself .
  • classinfo It can be a tuple of a class object , as long as class Is a subclass of any of the candidate classes , Then return to True
  • isinstance(object, classinfo) Method is used to determine whether an object is a known type , similar type().
  • type() A subclass is not considered a superclass type , Do not consider inheritance relationships .
  • isinstance() Think of a subclass as a superclass type , Consider inheritance relationships .
  • If the first parameter is not an object , Then return forever False.
  • If the second parameter is not a class or a tuple of class objects , Will throw out a TypeError abnormal
  • hasattr(object, name) It is used to determine whether the object contains the corresponding properties
  • getattr(object, name[, default]) Used to return an object property value
  • setattr(object, name, value) The corresponding function getattr(), Used to set property values , The attribute does not necessarily exist
  • delattr(object, name) Used to delete properties
  • class property([fget[, fset[, fdel[, doc]]]]) Used to return property values in a new class .
    • fget -- Gets the value of the property
    • fset -- A function that sets the value of a property
    • fdel -- Deletes the attribute value function
    • doc -- Attribute description information

Magic methods

Magic methods are always surrounded by double underscores , for example __init__.

The magic method is object-oriented Python Everything , If you don't know the magic method , It means you haven't realized the object-oriented Python A powerful .

By magic “ magic power ” Reflected in that they can always be called automatically at the right time .

The first parameter of the magic method should be cls( Class method ) perhaps self( Example method ).

  • cls: Represents the name of a class
  • self: Represents the name of an instance object

The basic magic method

  • __init__(self[, ...]) Constructors , Initialization method called when an instance is created
  • __new__(cls[, ...]) The first method called when an object is instantiated , Calling __init__ Before initialization , First call __new__.
    • new__ At least one parameter cls, Represents the class to instantiate , This parameter is instantiated by Python The interpreter automatically provides , The following parameters are passed directly to __init.
    • new__ Instantiate the current class , And return the instance to , Pass to __init__ Of self. however , Yes __new, It doesn't have to go into __init__, Only __new__ Back to , The current class cls Example , Current class __init__ To enter
    • if __new__ The current class is not returned correctly cls Example , that __init__ Will not be called , Not even an instance of the parent class , There will be no __init__ Called
  • __new__ The main way is when you inherit something immutable class when ( such as int, str, tuple), Give you a way to customize the instantiation process of these classes
  • del(self) Destructor , Methods that are called when an object is about to be recycled by the system
  • str(self):
    • When you print an object , Trigger __str__
    • When you use %s When formatting , Trigger __str__
    • str Strong conversion of data types , Trigger __str__
  • repr(self):
    • repr yes str The spare tire of
    • Yes __str__ When it comes to execution __str__, It didn't come true __str__ When , perform __repr__
    • repr(obj) The result of the built-in function is __repr__ The return value of
    • When you use %r When formatting Trigger __repr__

str(self) The returned results are readable . in other words ,str It's about getting information that people can read , Like the following '2019-10-11' equally .

repr(self) The return result of should be more accurate . How do you say ,repr The purpose of existence is to debug , Easy for developers to use

Arithmetic operator

Type factory function , refer to “ Create objects not through classes but through functions ”

class C:
    pass


print(type(len))  # <class 'builtin_function_or_method'>
print(type(dir))  # <class 'builtin_function_or_method'>
print(type(int))  # <class 'type'>
print(type(list))  # <class 'type'>
print(type(tuple))  # <class 'type'>
print(type(C))  # <class 'type'>
print(int('123'))  # 123

#  In this case list The factory function processes a primitive ancestor object into a list object .
print(list((1, 2, 3)))  # [1, 2, 3]
 Copy code 
  • add(self, other) The act of defining addition :+
  • sub(self, other) Define the act of subtraction :-
  • mul(self, other) Define the behavior of multiplication :*
  • truediv(self, other) The act of defining division :/
  • floordiv(self, other) Define the behavior of integer division ://
  • mod(self, other) Define the behavior of the modulus algorithm :%
  • divmod(self, other) Definition should be divmod() Behavior at call time
  • divmod(a, b) Combine the results of divisor and remainder operations , Returns a tuple containing quotient and remainder (a // b, a % b)
  • pow(self, other[, module]) Definition should be power() Call or ** The act of calculating
  • lshift(self, other) Define the behavior of bitwise left shift :<<
  • rshift(self, other) Define the behavior of bitwise right shift :>>
  • and(self, other) Define the behavior of biting and manipulation :&
  • xor(self, other) Defines the behavior of bitwise exclusive or operations :^
  • or(self, other) To define the act of biting or manipulating :|

Inverse arithmetic operator

Inverse magic cube method , Keep one-to-one correspondence with arithmetic operators , The difference is that there is one more magic method of inverse operation “r”. Called when the file left operation does not support the corresponding operation .

  • radd(self, other) The act of defining addition :+
  • rsub(self, other) Define the act of subtraction :-
  • rmul(self, other) Define the behavior of multiplication :*
  • rtruediv(self, other) The act of defining division :/
  • rfloordiv(self, other) Define the behavior of integer division ://
  • rmod(self, other) Define the behavior of the modulus algorithm :%
  • rdivmod(self, other) Definition should be divmod() Behavior at call time
  • rpow(self, other[, module]) Definition should be power() Call or ** The act of calculating
  • rlshift(self, other) Define the behavior of bitwise left shift :<<
  • rrshift(self, other) Define the behavior of bitwise right shift :>>
  • rand(self, other) Define the behavior of biting and manipulation :&
  • rxor(self, other) Defines the behavior of bitwise exclusive or operations :^
  • ror(self, other) To define the act of biting or manipulating :|

Incremental assignment operation

  • iadd(self, other) Define the behavior of assignment addition :+=
  • isub(self, other) Define the behavior of subtraction by assignment :-=
  • imul(self, other) Define the behavior of assignment multiplication :*=
  • itruediv(self, other) Define the behavior of assignment division :/=
  • ifloordiv(self, other) Defines the behavior of division of assigned integers ://=
  • imod(self, other) Define the behavior of assignment modulus algorithm :%=
  • ipow(self, other[, modulo]) Define the behavior of the assignment power operation :**=
  • ilshift(self, other) Defines the behavior of bitwise shift of assignment :<<=
  • irshift(self, other) Defines the behavior of bitwise right shifting of assignment :>>=
  • iand(self, other) Define the behavior of assignment bitwise and operation :&=
  • ixor(self, other) Define the behavior of bitwise exclusive or operation of assignment :^=
  • ior(self, other) Defines the behavior of assignment by bit or operation :|=

Unary operator

  • neg(self) Define positive behavior :+x
  • pos(self) Define the behavior of the minus sign :-x
  • abs(self) Definition should be abs() Behavior at call time
  • invert(self) Define the act of bitwise negation :~x

Attribute access

  • getattr(self, name): Defines the behavior when a user tries to get a nonexistent property .
  • getattribute(self, name): Defines the behavior of the class when its properties are accessed ( Call the method first , See if the property exists , If it does not exist , And then call __getattr__).
  • setattr(self, name, value): Defines the behavior when a property is set .
  • delattr(self, name): Defines the behavior when an attribute is deleted .

The descriptor

A descriptor is a property that assigns an instance of a particular type of class to another class .

  • get(self, instance, owner) Used to access properties , It returns the value of the property .
  • set(self, instance, value) It will be called in the attribute assignment operation , Don't return anything .
  • del(self, instance) Control delete operation , Don't return anything .

Custom sequence

agreement (Protocols) Very similar to interfaces in other programming languages , It specifies which methods you have to define . However , stay Python The agreement in this paper is not so formal . in fact , stay Python in , The protocol is more like a guide

Container type protocol

  • If you want the custom container to be immutable , You just need to define __len__() and __getitem__() Method .
  • If you want custom containers to be variable , except __len__() and __getitem__() Method , You also need to define __setitem__() and __delitem__() Two methods
  • len(self) Definition should be len() Behavior at call time ( Returns the number of elements in the container ).
  • getitem(self, key) Define the behavior of getting elements in the container , amount to self[key].
  • setitem(self, key, value) Defines the behavior of the specified element in the settings container , amount to self[key] = value.
  • delitem(self, key) Defines the behavior of deleting a specified element in a container , amount to del self[key]

iterator

  • Iteration is Python One of the most powerful features , Is a way to access collection elements .
  • An iterator is an object that remembers the traversal location .
  • The iterator object is accessed from the first element of the collection , Until all elements are accessed .
  • Iterators can only move forward and not backward .
  • character string , List or tuple objects can be used to create iterators
  • There are two basic ways to iterator :iter() and next().
  • iter(object) Function to generate iterators .
  • next(iterator[, default]) Returns the next entry for the iterator .
  • iterator -- Iteratable object
  • default -- Optional , Set to return the default value when there is no next element , If not set , No next element will trigger StopIterati- on abnormal
  • iter(se- lf) Define the behavior of elements in the iteration container , Returns a special iterator object , This iterator object implements next() Method and pass StopIteration The exception marks the completion of the iteration .
  • next() Returns the next iterator object .
  • StopIteration Exceptions are used to identify the completion of an iteration , To prevent infinite loops , stay next() Method, we can set to trigger after completing the specified number of cycles StopIteration Exception to end the iteration

generator

  • stay Python in , Used yield The function of the is called the generator (generator).
  • Different from ordinary functions , A generator is a function that returns an iterator , Can only be used for iterative operations , It's easier to understand that a generator is an iterator .
  • During the call generator run , Every encounter yield Function will pause and save all current running information , return yield Value , And next time next() Method to continue from the current location .
  • Call a generator function , Returns an iterator object

copyright notice
author[chaoyu],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301536426877.html

Random recommended