Python Basic Learning and Example Basic Usage and Notes

  • 2021-06-28 13:21:45
  • OfStack

This paper gives an example of Python basic learning and its basic usage and precautions.Share it for your reference, as follows:

Preface

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

Classes of Python

When an instance of the Python class is called first unew_uMethod, returns an instance object of the class, which is uinit_uThe first parameter of the method, self, is unew_uReturn value of

(1) Class access control:

(1) Default: member functions and member variables in Python are public (public). There are no keywords like public, private in python to modify member functions and member variables.

(2) Private: To define a private variable in python, simply add "u" before the variable name or function name.Two underscores, then this function or variable is private

Principle: Internally, python uses an name mangling technology that will umembername instead of _classname_umembername, that is, in the internal definition of a class, all names starting with a double underscore are "translated" with a single underscore and a class name preceded by it.

For example, to ensure that private variables are not accessible outside of class, Python automatically defines u within the classReplace the name of the spam private variable with _classname_uspam (note that there is an underscore before classname and two before spam), so the user accesses u externallyspam will prompt you to find no corresponding variable.

Note: Private variables and methods in python are still accessible;The access methods are as follows:

私有变量:实例._类名__变量名

私有方法:实例._类名__方法名()

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

In fact, Python does not have real privatization support, but can be used to get pseudo-privatization by underlining.Therefore, 1 generally requires a unified 1 specification:

1_xxx: Member variables that start with a single underscore are called protected variables (protected), meaning that only class instances and subclass instances can access them.

Access is required through the interface provided by the class;Not available' from <module> import * 'Import;

(2)uxxx: Private variable/method name in the class (the function of Python is also an object, so it makes sense for a member method to be called a member variable).

Double Underline starts with private members, meaning that only class objects can access it, not even subclass objects.

3_uxxx_uSystem Definition Name, with a "double underscore" around it representing the identification specific to the particular method in python, such as uinit_u()A constructor that represents a 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' # Translate to self._A__name='python'
class B(A):
  def func(self):
    print self.__name # Translate to print self._B__name
instance=B()
#instance.func()# Report errors: AttributeError: B instance has no attribute '_B__name'
print instance.__dict__
print instance._A__name

Output results:

{'_A__name': 'python'}
python

Note: When the B class is named A, instance.func() can be called directly

(3) Inheritance of the Python class:

Like other OOP languages, the python class can use the inheritance function and does not allow multiple inheritance, but it can be achieved through multilevel inheritance.

(1) Inheritance method: the class name of the derived class is written to the parent class in ();

(2) Constructor: Constructor in subclass plus super (subclass, self). uinit_u(Parameter 1, parameter 2,....);

(3) Order of instantiation: Instantiate object c-- > c Call Subclass_uinit_u(): > Subclass_uinit_()Inherit parent class_uinit_u()----- > Call parent class_uinit_();

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

(5) Method override: a method with the same name as the parent class is defined in a subclass, and the overridden method is used when an instance of the subclass is called;

(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 a subclass and a parent, the method of the subclass overrides the method of the parent class, and the method of the subclass is called when the code is run;

Note: Polymorphism implements the development-closure principle:

(1) Open to Extensions (Open for extension): Allow subclasses to override method functions;
(2) Closed to modification (Closed for modification): directly inherit parent method functions without overriding;

Additional knowledge of the Python class

(1) The difference between self and cls in python:

(1) self represents a specific instance itself, equivalent to this of php.If you use staticmethod, you can ignore this self and use this method as a normal function.

(2) cls represents the class itself;

@staticmethod: Method that can only be called with a class name;
@classmethod: A method that can be called either by an instance or by a class name;

(2) Search order for multiple inheritance methods:

For most applications, in the simplest case, you can assume that searching for attributes inherited from the parent class is depth-first, left-to-right, and will not search twice in the same class when there is overlap in the hierarchy.Therefore, if a 1 attribute is not found in DerivedClassName, it will be searched in Base 1, then (recursively) in the base class of Base 1, if it is not found there, then in Base2, and so on.

The reality is a little more complicated than this;The method parsing order changes dynamically to support collaborative calls to super().This is called a subsequent method call in some other multiple inheritance languages and is more powerful than the super call in a single inheritance language.

Changing the order dynamically is necessary 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 object, so any case of multiple inheritance provides more than one path to object.To ensure that the base class is not visited more than once, the dynamic algorithm linearizes the search order in a special way, preserving the left-to-right order specified by each class, invoking each parent class only once, and keeping it monotonous (that is, a class can be subclassed without affecting its parent's priority).

More readers interested in Python-related content can view this site's topics: Introduction and Advanced Python Object-Oriented Programming, Python Data Structure and Algorithms, Python Function Usage Skills Summary, Python String Operation Skills Summary, Python Coding Operation Skills Summary, and Python Introduction and Advanced Classic Tutorials.

I hope that the description in this paper will be helpful to everyone's Python program design.


Related articles: