python system learning [2]

Posted by oneofayykind on Tue, 14 Dec 2021 19:44:32 +0100

Previous: Reference blog

1. Exception handling

reference resources

1.1 an exception

try:
    Code that may cause exceptions
except Exception1:
    exception handling
try:
    a = int(input("First integer"))
    b = int(input("Second integer"))
    result = a/b
    print("The result is", result)
except ZeroDivisionError:
    print("Divisor 0 is not allowed")
print("Program end")

1.2 multiple anomalies

Multiple exception structures:
The order of capturing a field is in the order of subclass before parent class. In order to avoid missing possible exceptions, BaseException can be added at the end

try:
    Code that may cause exceptions
except Exception1:
    exception handling
except Exception2:
    exception handling
except BaseException:
    exception handling
try:
    a = int(input("First integer"))
    b = int(input("Second integer"))
    result = a/b
    print("The result is", result)
except ZeroDivisionError:
    print("Divisor 0 is not allowed")
except ValueError:
    print("Only digital strings can be output")
print("Program end")

1.3 try... exception... else structure

If no exception is thrown in the try block, else block is executed; if an exception is thrown in the try block, except block is executed

try:
    a = int(input("First integer"))
    b = int(input("Second integer"))
    result = a/b
    print("The result is", result)
except BaseException as e:
    print("Error ", e)
else:
    print("The calculation result is", result)



1.4 try... exception... else... finally structure

finall is executed no matter whether an exception occurs or not. It can often be used to release the resources applied in the try block.

try:
    a = int(input("First integer"))
    b = int(input("Second integer"))
    result = a/b
    print("The result is", result)
except BaseException as e:
    print("Error ", e)
else:
    print("The calculation result is", result)
finally:
    print("Thank you for your use")


1.5 common Python exceptions

1.6 Traceback

reference resources

  • traceback.print_exc()
  • traceback.format_exc()
  • traceback.print_exception()

2. Classes and objects

2.1 object oriented and Programming Oriented Ideas


Object oriented: only find the participants in this matter, and don't care about the process.

2.2 class creation

The most important concepts of object-oriented are Class and Instance. We must keep in mind that Class is an abstract template, such as Student Class, and Instance is a specific "object" created according to Class. Each object has the same method, but its data may be different.

class Student(object):
    pass
  • Definition: in Python, a class is defined through the class keyword:
  • Class is followed by the class name, that is, Student. The class name usually starts with a capitalized word, followed by (object), which indicates which class the class inherits from. We will talk about the concept of inheritance later. Generally, if there is no appropriate inheritance class, use the object class, which is the class that all classes will inherit in the end.
  • Class composition:
    (1) Class properties
    (2) Example method
    (3) Static method
    (4) Class method
class Student:
    native_pace = 'Heilongjiang'  # Variables written directly in a class are called class attributes
    def __init__(self, name, age):  #  self.name is called an entity attribute. An assignment operation is performed to assign the name of the local variable to the entity attribute
        self.name = name
        self.age = age
    def eat(self):  # Example method
        print("The students are eating")
    @staticmethod
    def method():  # self is not allowed in static methods
        print("I used it staticmethod So I'm a static method")
    @classmethod
    def cm(cls):
        print("I'm a class method because I use classmethod Modify")

# Functions defined outside a class are called functions, and methods defined within a class are called methods
def drink(): # function
    print("drink water")

2.3 object creation

# Create object of Student class
stu1 = Student("Zhang San", 20)
print(id(stu1))
print(type(stu1))
print(stu1)

4563833760
<class 'main.Student'>
<main.Student object at 0x1100693a0>
The bottom hexadecimal to decimal is actually the number above

# Create object of Student class
stu1 = Student("Zhang San", 20)
print(id(stu1))
print(type(stu1))
print(stu1)
print(id(Student))
print(type(Student))
print(Student)

4511086720
<class 'main.Student'>
<main.Student object at 0x10ce1b880>
140274309310848
<class 'type'>
<class 'main.Student'>

There will be a class pointer in the instance object to the class object it creates

  • Student is a class object
  • Instance objects are created from class objects
# Create object of Student class
stu1 = Student("Zhang San", 20)
stu1.eat()  # Class can call instance methods and property object names Method name ()
print(stu1.name)
print("-------")
Student.eat(stu1)  # And stu1 Eat () has the same function. It calls the eat method in Student
# The eat method requires that you pass in self, that is, the object itself, so you must pass in parameters
# Class name Method name (object of class) -- > is actually self at the method definition

2.4 class attribute, class method, static method and instance method

Everything in python is an object, even if it is a class, it is actually a kind of object, which we call class object.
Instance method, class method and static method
Class properties, class methods, and static methods

  • Class attribute: the attribute owned by a class object is called class attribute, which is shared by all instance objects of the class. Class properties can be accessed using class objects or instance objects. Class attributes, such as: native_pace
  • Class methods: similar to class attributes, the methods owned by class objects are called class methods. Methods decorated with @ classmethod and directly accessed by class name
  • Static method: the method modified by @ staticmethod and directly accessed by class name. In development, we often need to define some methods related to classes, but we do not need to reference classes or instances during implementation, such as setting environment variables, modifying variables of another class, etc. At this time, we can use static methods. Static methods eliminate unnecessary parameter passing, which is conducive to reducing unnecessary memory occupation and performance consumption.

(1) Class properties:

# Use of class properties
print(Student.native_pace)
stu1 = Student("Zhang San", 20)
stu2 =  Student("Li Si", 30)
print(stu1.native_pace)
print(stu2.native_pace)
Student.native_pace = 'Tianjin'
print(Student.native_pace)
print(stu1.native_pace)
print(stu2.native_pace)

Heilongjiang
Heilongjiang
Heilongjiang
Tianjin
Tianjin
Tianjin

  • Whether it is through an instance object or a class object, the class properties obtained are the same. Therefore, when the data recorded by the instance object of the class is always consistent, the attribute can be defined as a class attribute.
  • Class properties can be modified through class objects, but class properties cannot be modified through instance objects. There will be no error when using an instance object to modify a class attribute, because at this time, an instance attribute with the same name as the class attribute is actually defined for the instance object of the class.
  • In the process of using, we should try to avoid the same name of class attribute and instance attribute. If there is an instance property with the same name, the instance object will access the instance property first.
  • Instance properties require each object to open up a separate memory space for recording data, while class properties are shared by the whole class, occupying only one memory, which saves more memory space.

(2) Class method

stu1 = Student("Zhang San", 20)
stu2 =  Student("Li Si", 30)
Student.cm()
stu1.cm()
stu2.cm()

I am a class method because I use classmethod to decorate it
I am a class method because I use classmethod to decorate it
I am a class method because I use classmethod to decorate it

  • To define a class method, you need to use the decorator @ classmethod to identify it as a class method, and the first parameter of the class method must be a class object, generally taking cls as the first parameter. Otherwise, the class method is not successfully defined and cannot be used through the class object.
  • Class methods can be called either through classes or through instances

(3) Static method:

stu1 = Student("Zhang San", 20)
Student.method()
stu1.method()

I use static method for modification, so I am a static method
I use static method for modification, so I am a static method

(4) Instance method: Python's instance method is the most used and the most common.

2.5 dynamic binding properties and methods

Python is a dynamic language that can dynamically bind properties and methods after creating objects.
(1) Dynamic binding properties

class Student:
    native_pace = 'Heilongjiang'  # Variables written directly in a class are called class attributes
    def __init__(self, name, age):  #  self.name is called an entity attribute. An assignment operation is performed to assign the name of the local variable to the entity attribute
        self.name = name
        self.age = age
    def eat(self):  # Example method
        print(self.name + "be at  table")

stu1 = Student("Zhang San", 20)
stu2 =  Student("Li Si", 30)
print(id(stu1))
print(id(stu2))
print("----by stu2 Dynamically bind gender attributes-----")
stu2.gender = 'female'
print(stu1.name, stu1.age)
print(stu1.name, stu1.age,stu2.gender)
# If you want to output the gender of stu1, the program will report an error. Because we only dynamically bind stu2, not stu1

4565257088
4565850240
----Dynamically bind gender attribute for stu2-----
Zhang San 20
Zhang San, 20 female

(2) Dynamic binding method

  • Dynamically add methods without parentheses, which are only required when calling
class Student:
    native_pace = 'Heilongjiang'  # Variables written directly in a class are called class attributes
    def __init__(self, name, age):  #  self.name is called an entity attribute. An assignment operation is performed to assign the name of the local variable to the entity attribute
        self.name = name
        self.age = age
    def eat(self):  # Example method
        print(self.name + "be at  table")
stu1 = Student("Zhang San", 20)
stu2 =  Student("Li Si", 30)
def show():
    print("Defined outside the class is called a function")
# Dynamic binding function
stu1.show= show
stu1.show()
stu2.show() # An error is reported because stu2 does not dynamically bind the show method

Defined outside the class is called a function

3. Object oriented

3.1 three characteristics of object-oriented

Reference: encapsulation, inheritance, polymorphism

(1) Encapsulation

  • Encapsulation is an abstraction of specific objects, that is, some parts are hidden and can not be seen outside the program, which means that other programs cannot be called. Class can be called outside.
  • Encapsulate objects and attributes so that different objects have different attributes.
  • Private properties, see the following code example.
class Student:
    def __init__(self, name, age):
        self.name = name
        self.__age = age  # age doesn't want to be used externally, so it's added__ Become private variable
    def show(self):
        print(self.name, self.__age)

stu1 = Student("Zhang San", 20)
stu1.show()  # Use name and age outside the class
print(stu1.name)  # No error reporting
# print(stu1.__age)  # An error is reported because the instance object cannot use private variables outside the class
print(stu1._Student__age)  # Outside the class_ Student__age for access
# The encapsulation of python depends on the programmer's consciousness. Don't access private variables when you see them. You can access them if you have to, but this access method is not recommended

3.2 succession

5 modules:
(1) : call the parent property method directly
(2) : force a call to a parent class private property method
(3) : override parent property method
(4) : call the _ init method of the parent class
(5) : inherit parameters during parent class initialization

(1) Call the parent property method directly

Subclasses inherit all properties and methods of the parent class. Instantiated objects of subclasses can use all properties and methods of the parent class, but pay attention to private properties and methods.

(2) Force call to parent private property method

If the method of the parent class is private, such as def__ Action (self) if you call it again, you will be prompted that there is no such method. In fact, the compiler changed the name of this method to_ Parent class name__ Method name ()_ Father__action(), if called forcibly, can be as follows: super()_ Father__action()

(3) Override parent property method

  • If the subclass does not override the method of the parent class, the method of the parent class will be called when the method is called,
  • When a subclass overrides the method of the parent class, it calls its own method by default.
  • In addition, if the subclass Son overrides the method of the parent class Father, if you want to call the action method of the parent class, you can use super()

(4) Call the _ init method of the parent class

  • If the subclass itself is defined__ init__ Method, indicating that the subclass has overridden the initialization method of the parent class, so the subclass cannot directly call the properties of the parent class.
  • Modification method: you can modify the__ init__ Call the parent class in the init__ Method so that it can be called
class Father():
    def __init__(self):
        self.a='aaa'
 
class Son(Father):
    def __init__(self):
        super().__init__()
        #You can also use father__ init__ (self) the self in this must be added
son=Son()
print(son.a) 

(5) Inherit parameters during parent class initialization

class Father():
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def dev(self):
        return self.a - self.b
 
 #Call the parent class to initialize parameters a,b and add additional parameters c
class Son(Father):
    def __init__(self,a,b,c=10):  # Fixed value: for example, the default value is c=10, and c can also be assigned explicitly
        Father.__init__(self,a,b)  
        # Or write the following sentence:
        # super().__init__(self,a,b)
        self.c = c
    def add(self):
        return self.a+self.b
    def compare(self):
        if self.c > (self.a+self.b):
            return True
        else:
            return False
        
son=Son(1,2)         # Since c defaults to 10 during initialization, c can be expressed without display
print(son.dev())     # Call the parent dev function
print(son.add())     # add function of subclass itself
print(son.compare()) # compare function of subclass itself

result:
-1
3
True

3.3 Object class

  • The object class is the base class of all classes in Python. If a class is defined without specifying which class to inherit, it inherits the object class by default. The object class is the parent class of all classes, so all classes have the properties and methods of the object class.
  • The built-in function dir() can view all properties and methods of the specified object.
  • The Object class has a__ str__ The () method is used to return a description of the "Object", corresponding to the built-in function str(). It is often used in the print() method to help us view the Object information, so we often__ str__ () to rewrite.
class Student:
    pass
stu = Student()
print(dir(stu))

['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref']

class Student:
    pass
stu = Student()
print(stu)  # <__main__.Student object at 0x100b6ab80>
class Student:
    def __init__(self, name, age):
        self.name = name
        self.__age = age
    def __str__(self):
        return "My name is{0},this year{1}year".format(self.name, self.__age)
stu = Student("Zhang San", 20)
print(stu)  # My name is Zhang San. I'm 20 years old
# Called by default__ str__ method

Once right__ str__ If rewritten, the memory address will not be output, but the rewritten content will be output.

3.4 polymorphism

reference resources

  • Although Person does not inherit the Animal class, but Person also has the eat() method, so you can also use the fun() function, which is a difference between static and dynamic languages.

3.5 special properties and methods


(1) Special properties

class A:
    pass
class B :
    pass
class C(A,B):
    def __init__(self,name):
        self.name = name
x = C("Jack")
print(x.__dict__)  # {'name': 'Jack'}
print(C.__dict__)  # {'__module__': '__main__', '__init__': <function C.__init__ at 0x10e185430>, '__doc__': None}
print(x.__class__)  # <class '__ main__. C '> the class to which the output object belongs
print(C.__bases__)  # (<class '__main__.A'>, <class '__main__.B'>)# Tuple of output parent class
print(C.__base__)  #<class '__ main__. A '> output the nearest parent class
print(C.__mro__)  #View the inheritance relationship and hierarchy relationship of the class (< class' _main _. C '>, < class' _main _. A' >, < class' _main _. B '>, < class' object' >)
print(A.__subclasses__())  #Output subclass list [< class' _main_. C '>]

(2) Special method
reference resources

  • You can override built - in methods to implement custom built - in methods
  • Example: if you want an object to have the addition feature, you must override it__ add__ () function
a = 20
b = 100
c = a + b
d = a.__add__(b)
print(c)
print(d)

class Student:
    def __init__(self, name):
        self.name = name

stu1 = Student("Zhang San")
stu2 = Student("Li Si")
s = stu1 + stu2
print(s)  # report errors
# TypeError: unsupported operand type(s) for +: 'Student' and 'Student'
# If you do not want to add, override__ add__ () function
class Student:`Insert the code slice here`
    def __init__(self, name):
        self.name = name
    def __add__(self, other):
        return self.name + other.name

stu1 = Student("Zhang San")
stu2 = Student("Li Si")
s = stu1 + stu2
print(s)  # this one and that one

new__ And__ init

reference resources: Difference between new and init
When to use new, it will be used in singleton mode

  • In fact__ init__ Function is not a true constructor__ init__ Method initializes variables after the object is created. What really creates an instance is__ new__ method.
  • __ new__ Method is used to create an object and return it. It is called automatically when the object is returned__ init__ Method.
  • __ new__ Methods are static, and__ init__ Is an instance method.

Shallow and deep copy of class 3.6


Direct assignment, shallow copy and deep copy

  • Assignment: simply copy the reference of the object. The IDs of the two objects are the same.
  • Shallow copy: creates a new composite object that shares child objects in memory with the original object.
  • Deep copy: create a new composite object and copy all sub objects recursively. The new composite object has no association with the original object. Although immutable sub objects are actually shared, their mutual independence is not affected.
  • For immutable objects, the above three methods generate references to the original object, and there is no saying of copying.

Topics: Python Pycharm crawler