A detailed explanation of basic Python learning and examples


In this article, the basic learning of Python and the basic usage and precautions of instances are described. To share with you for your reference, as follows:


Compared with other programming languages, python adds classes to the language with very few new syntax and semantics. Python classes provide all the standard features of object-oriented programming: class inheritance mechanism allows multiple base classes, derived classes can cover any method of its base class, and a method can call a method with the same name in the base class. Objects can contain any number and type of data. Like modules, classes have Python’s natural dynamic nature: they are created at run time and can be modified after creation.

Class Python

When a python class instance,First, call the new method to return the instance object of the class. This instance object is the first parameter of the init method self, that is, self is the return value of new method

(1) Class access control:

① Default: both member functions and member variables in Python arePublicIn Python, there are no keywords like public and private to modify member functions and member variables.

② Private: to define a private variable in Python, you only need toIf you underline the variable name or function name, the function or variable is private

Principle: internally, python uses a name mangling technology,Replace “membername” with “classname”In other words, in the internal definition of a class, all names starting with double underscores are “translated” into the form of single underscores and class names.

For example: in order to ensure that private variables cannot be accessed outside of class, python will automatically replace the name of the private variable of \\\\\\\\\\\\\\\\\\\\\\\\\\\\.

Note: private variables and private methods in Python are still accessible; the access methods are as follows:

Private variable: instance. Class name. Variable name

Private method: instance. Class name. Method name ()

(2) Privatization support for Python classes and class members:

In fact, python doesn’t have real privatization support, but you can use underscores to get pseudo privations. Therefore, unified specifications are generally needed:

① Zhu XXX: the member variable starting with “single underscore” is calledProtected means that only class instances and subclass instances can access these variables

It needs to be accessed through the interface provided by the class; can’t use the ‘from <module> import *Import;

② (XXX: the private variable / method name in the class (Python’s function is also an object, so it is also possible to call member methods as member variables),

“Double underscores” begin with private members, which means that only class objects can access this data, and even subclass objects cannot access this data;

③ The system defines the name, with a “double underscore” in front of it representing the special identification of the special method in Python, such as “init” representing the constructor of the class;

Note: Python derived classes can have the same name as the parent class, so private variables can be used in this case:

class A():
  def __init__(self):
    Self. Name = Python
class B(A):
  def func(self):
    Print self. "Name" translates to print self. "B" name
#Instance. Func(): attributeerror: B instance has no attribute '; B name'
print instance.__dict__
print instance._A__name

Output results:

{‘_A__name’: ‘python’}

Note: when class B is named a, instance. Func() can be called directly

(3) Inheritance of Python class:

Python classes, like other OOP languages, can use inheritance function, and multiple inheritance is also not allowed, but it can be implemented through multi-level inheritance.

(1) Inheritance method: write the class name of the parent class in () of the class name of the derived class;

(2) Constructor: add super (subclass, self) to the constructor in the subclass );

(3) Instantiation order: instantiate Object C — > C call subclass — > subclass — inherit parent class — — — > call parent class —;

(4) Functions to determine inheritance: isinstance() and issubclass(), where isinstance() is used to check instance type; issubclass() is used to check class inheritance;

(5) Method rewrite: a method with the same name as the parent class is defined in the subclass, and the overridden method will be used when the subclass instance calls;

(6) Subclass override constructor: the subclass constructor does not use super to call the parent class;

(7) Polymorphism: when a method with the same name exists in both the subclass and the parent, the method of the subclass covers the method of the parent. When the code runs, the method of the subclass will be called;

Note: polymorphism realizes the development closure principle:

① Open for extension: allows subclasses to override method functions;
② Closed for modification: does not override, directly inherits the function of the parent method;

Other knowledge of Python classes

(1) The difference between self and CLS in Python:

Self represents a specific instance itself, equivalent to this in PHP. If you use static method, you can ignore this self and use this method as a normal function;

CLS represents the class itself;

@Static method: a method that can only be called with the class name;
@Classmethod: a method that can be called by both instance and class name;

(2) Multiple inheritance method search order:

For most applications, in the simplest case, you can think that the operation of searching the inherited attributes from the parent class is depth first, from left to right. When there is overlap in the hierarchy, it will not search twice in the same class. So if a property is not found in derivedclassname, it is searched in base1, then (recursively) in base1’s base class, if it is not found there, then in base2, and so on.

The real situation is more complicated than this; the method parsing order is dynamically changed to support cooperative calls to super(). This method is called subsequent method call in some other multiple inheritance languages, which is more powerful than super call in single inheritance languages.

It is necessary to change the order dynamically, because all cases of multiple inheritance show one or more diamond associations (that is, at least one parent class can be accessed by the lowest class through multiple paths). For example, all classes inherit from the object, so any multiple inheritance situation provides more than one path to the object. In order to ensure that the base class will not be accessed more than once, the dynamic algorithm will use a special way to linearize the search order, keep the order specified by each class from left to right, only call each parent class once, and keep monotony (that is, a class can be subclassed without affecting the priority of its parent class).

For more information about python, you can see the following topics: introduction and advanced course of Python object-oriented programming, python data structure and algorithm, summary of Python function use skills, summary of Python string operation skills, summary of Python coding operation skills, and introduction and advanced classic course of Python

I hope that this article is helpful for Python programming.