Learning notes for beginners of python. 3 program design

        python programs support two programming methods: process oriented programming and object-oriented programming. This paper mainly discusses object-oriented programming.

Certain semantic class

        class is the basis of object-oriented. class is used to define classes in python. Classes are mainly composed of attributes and methods.

II. Defining attributes

        Properties, also known as member variables, can be any data type. Attributes are divided into class attributes (class variables) and instance attributes (instance variables). Class properties are common throughout the instantiated object, defined in the class and outside all methods. Instance properties are data unique to each instance.

        Attributes are also divided into public attributes and private attributes. Private property names are preceded by two underscores__ At the beginning, private properties cannot be accessed directly outside the class.

        Any attribute of a class can be referenced in a method of the class. The reference method of class attribute is "class name. Class attribute name", and the reference method of other attributes is "self. Attribute name".

class A:
    x = 2  # Class attribute x
    __y = 0  # Private class attribute y

    def __init__(self, p):  # Construction method
        self.z = p
        self.__w = 0

    def add(self):
        self.__y += 10
        self.__w += 20

    def disp(self):
        print(A.x, self.__y, self.z, self.__w)

A.x += 1
a = A(10) #It is very similar to the structure in c language
b = A('Bye')

Three definition methods

        Methods, also known as member functions, are used to represent the behavior of objects. Defs are used inside a class to define a method. Different from the definition of general functions, class methods must contain a parameter self, which is the first parameter. Self represents the instance of the class, that is, the address of the current object, and self.claa points to the class. Note that self is not a python keyword.

        Any method of a class can be called in the method of "self. Method name (parameter)".

          Class has a name__ init__() Special methods. This method is used to assign values to the properties of an object while instantiating it. Other methods are as follows:

__del__ #Destructor, used when releasing an object.
__repr__ #The conversion is implemented on output.
__setitem__ #Assign values by index.
__getitem__ #Get the value according to the index.
__len__ #Get the length.
__cmp__ #Comparison operation.
__call__ #Function call.
__add__,__sub__,__mul__,__truediv__,__mod__,__pow__ #Corresponding to mathematical operation respectively.

IV. definition object

          In python, everything is an object. The defined class itself is also an object with the name of the class, which is called class object. Users can reference class properties by using "class object. Class property". You cannot reference other properties and other methods with classes through class objects.

        Instance object is the product of class object instantiation. The general format of defining instance object is: instance object name = class name ([parameter list]). Through the instance object, you can reference all non private properties and fis methods of the class. For the instance object, the class property does not exist.

Parameter transfer of five methods

        1) The parameter is an immutable data type

        In this case, the parameter is passed in the form of value copy, that is, the argument value is directly assigned to the corresponding formal parameter, and then the called method is executed. The argument value will not be changed when it is returned.

class A:
    def sum(self, n, s):
        s = n*(n+1)//2 # the values here are all formal parameters, the same as those in c language.

a = A()
s = 0
a.sum(5, s)

The output s is 0         

         2) The parameter is of variable data type

        When the parameter is a variable data type, the result of the formal parameter is passed to the argument( (I feel the smell inside the pointer)

        For example, the one above can replace s with a list.

class A:
    def sum(self, n, s):
        s.append(n*(n+1)//2) Do not assign values directly to # variable data types such as lists.

a = A()
s = []
a.sum(5, s)

        Objects in python consist of object names and instances. The address of the instance is stored in the object name. When calling, the value is passed, that is, the address stored in the parameter object name is copied to the formal parameter, so that the formal parameter and the actual parameter point to the same instance( Like a pointer...) If the instance is changed through the formal parameter, the instance pointed to by the argument also changes, which is equivalent to passing the change of the instance back to the argument. And c language functions can use a pointer as a variable is almost.

Vi. succession

        1) Single inheritance

        The basic format is as follows: in fact, it is easy to understand.

class Subclass name(Parent class name): 
Statement 1
sentence n

        The parent and child classes are defined in one scope. If the parent class is fixed in another module, it needs to be referenced with "module name".

        If you need the constructor of the parent class in a subclass, you need to explicitly call the constructor of the parent class or do not override the constructor of the parent class. If the subclass does not override__ init__(), When instantiating a subclass, the defined by the parent class will be called automatically__ init__(). The way to call the parent class to construct a method in a subclass is:


super().__init__(Parameter 1,Parameter 2,...)

  The return value of super () is a special object, which is specially used to call the properties in the parent class.

         Subclasses inherit all non private properties and methods of the parent class, but do not inherit private.

        When looking for properties or methods, subclasses have priority to look for themselves. If they can't find them, they will find the parent class. A subclass can define its own new attribute. If it has the same name as the parent class, the subclass's own attribute shall prevail. The method is the same.

class People:   #Define parent class
    def __init__(self, n, a, w):    #Construction method
        self.name = n
        self.age = a
        self.__weight = w

    def dispp(self):
        print("My name is %s,I weigh %s kilos"% (self.name, self.__weight), end='')

class Student(People):  #Define subclasses
    def __init__(self, n, a, w, g): #Construction method of subclass
        super().__init__(n, a, w)   #Call the constructor of the parent class
        #People can also be used here__ init__( self,n,a,w)
        self.grade = g

    def disps(self):
        super().dispp() #Call the constructor of the parent class
        print("My age is %d,and I\'m in %d grade." % (self.age, self.grade))

s = Student('John', 10, 50, 3)

        2) Multiple inheritance

         Multiple inheritance inherits multiple parent classes directly. It should be noted that if the method name is the same as that in the parent class and is not specified in the subclass, Python will search from left to right in writing order, that is, if the method is not found in the subclass, it will find whether the parent class contains the method from left to right.

class A:
    def disp(self):

class B(A):
    def disp(self):
        print("In B")
        super().disp()  #Call C's disp
        print('Out B')

class C(A):
    def disp(self):
        print("In C")
        super().disp()  #Call A's disp
        print('Out C')

class D(B, C):
    def disp(self):
        print("In D")
        super().disp()  #Call B's disp
        print('Out D')

print(D.__mro__)    #Output parsing order
d = D()

The output result of parsing sequence is:

(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

That is, when d.disp() is executed, the restricted disp() method of class D calls B first and then C because the inheritance order of class D is B first and then C. So, super().disp() in D.disp () first calls B.disp(), then calls C.disp(), and finally calls A.disp(). The results are as follows:

In D
In B
In C
Out C
Out B
Out D

VII. Exception handling

        The most common exception handling method in python is the try statement. Common exception types are as follows:

Exception     #Base class for common types. Common base class for all non-exit exceptions.
StopIteration     #The iterator has no more values. Signal the end from iterator.__next__().
FloatingPointError     #Floating point calculation error. Floating point operation failed.
ZeroDivisionError     #Error in modulo or divide by zero. Second argument to a division or modulo operation was zero.
AssertionError     #Raised when the assert statement fails. Assertion failed.
FileExistsError     #Create an existing file or directory. File already exists.
FileNotFoundError     #The corresponding file or directory was not found. File not found.

        Simple application:

    x = 4/0
except ZeroDivisionError:
    print('0 Cannot be divisor!!')

You can throw an exception using raise.

def openfile(name):
        f = open(name, 'r')
        raise Exception('')
    print(name+'File opened successfully')

name = 'xyz.txt'
    print(name+'file does not exist')

        When executing the above procedures, if a file exists, it will be prompted that it has been opened successfully; On the contrary, an Exception is thrown and caught by the following Exception.

        In fact, asserting assert Exception is equivalent to:

if not Exception:
    raise AssertionError

Eight iterators and generators

        1) Iterator

        In python, string, list, tuple and dictionary types are iteratable objects, which are simply traversable.

        Iterators have two basic functions, iter() and next(). The former establishes the iterator object of the iteratable object, and the latter is used to return the next original of the iterator. At the end of the iteration, a StopIteration exception is thrown. For example:

a = [1, 2, 3, 4, 5]  # Define iteratable object a
it = iter(a)  # Establish the iteration object it of a
while True:
        x = next(it)  # Get the next element value
    except StopIteration:

next() can take one parameter:


Default is used to set the default value returned when there is no next element. If it is not set, a StopIteration exception will be triggered. Therefore, the above code is equivalent to the following:

a = [1, 2, 3, 4, 5]
it = iter(a)
while True:
    x = next(it, 'ero')
    if x == 'ero':

        2) Generator

        In python, functions that use one or more yield are called generators. The generator is a function that returns an iterator. Each time it runs to yield, it will pause and save the current running information, return the value of yield, and continue running from the current position the next time it executes next ().

def revstr(str):
    n = len(str)
    for i in range(n-1, -1, -1):
        yield str[i]

it = revstr('hello')
while True:
    x = next(it, '#')
    if x == '#':
    print(x, end='')

Above is a string inversion program.

Tags: Python

Posted on Wed, 01 Sep 2021 14:36:19 -0400 by KirstyScott