Object-oriented programming in Python

1) Object-oriented

Object Oriented is a software development method. Object-oriented is a method of understanding and abstracting the real world. It is the product of computer programming technology developed to a certain stage. Its proposal is relative to process-oriented.
Object Oriented Programming (Object Oriented Programming) method is to simulate the human way of thinking as much as possible, so that the software development method and process are as close as possible to the method and process of human understanding of the world and solving real problems, that is, to describe the problem space and The solution space of the problem is as consistent as possible in structure, and the entities in the objective world are abstracted into objects in the problem domain.
The difference between object-oriented and procedural-oriented is:

  • Process-oriented is a process-centered programming idea; object-oriented is an object-centric programming idea.
  • Process-oriented is to analyze the steps needed to solve the problem, and then use functions to realize these steps step by step; object-oriented is to decompose the constituent problems into individual objects, and then operate each object to realize it.
  • The core of process-oriented is function; the core of process-oriented is class and object.

The main concepts of object-oriented:

  • data abstraction
  • object
  • kind
  • inherit
  • polymorphism
  • messaging
  • data encapsulation
  • dynamic binding

2) Classes and Objects

Object-oriented programming takes objects as the core, and this method thinks that a program is composed of a series of objects. A class is an abstraction of the real world, including data representing static properties and operations on data, and an object is an instantiation of a class. Objects communicate with each other through message passing to simulate the relationship between different entities in the real world. In object-oriented programming, objects are the basic modules that make up a program.
The Python language has been an object-oriented language since its design, so it is easy to create classes and objects in Python.

1. Class definition

Class (Class) is a concept in object-oriented programming (OOP, Object-Oriented Programming) and is the basis of object-oriented programming. A class is the overall name of a group of species, such as humans, animals, plants, etc. In a programming language, a class is a user-defined reference data type, also known as a class type, similar to byte, short, int (char), Basic data types such as long, float, double, etc., the difference is that it is a complex data type. It is an abstraction of objects with the same or similar properties. It is essentially a data type, not data, so it does not exist in memory and cannot be directly manipulated. It becomes operable only when it is instantiated as an object.
The class definition includes:

  1. Class name - the name of the class, usually the first letter is capitalized to distinguish the class name from other variable names
  2. Attributes - characteristics used to describe things, such as a dog's breed, color, etc.
  3. Method - used to describe the behavior of something, such as a dog barking, running, etc.

In Python, use the class keyword to define a class, and its basic syntax is as follows:

 class 类名:   
      类的属性   
      类的方法 

For example: to define a dog class, the code is:

 class Dog   
            #属性  
            #方法  
           def eat(self):      
                  print(‘狗喜欢吃肉!’) 

2. Object creation

A class is a group of things with the same characteristics, and it cannot be specifically pointed to something, and an object is the embodiment of a class, a specific object in a class, so a class is an abstraction of an object, and an object is the concreteness of a class. The properties and methods of the class cannot be realized, only when it is specific to the object. In the Python language, the basic grammatical format for creating an object is:

对象名=类名()

3. Construction method and destruction method

In the Python program, there are two special methods, namely the construction method _init_() and the destructor method _del_(). The constructor is used to initialize the properties of the object, and the destructor is used to release the space occupied by the class and the object. Both constructors and destructors are called implicitly by the compiler. The order in which these methods are called depends on the order in which program execution enters and leaves the scope in which the object is instantiated. Generally speaking, the call order of the destructor method is opposite to that of the constructor method, but the storage class of the object can change the call order of the destructor function.

a. Construction method

The constructor has the function of initialization, that is, the method will be executed when the class is instantiated, that is, when an object is created, the constructor will be called immediately.
In a Python class, the syntax for manually adding a constructor is as follows:

def  __init__(self,...):
    代码块
b. Destruction method

When the object needs to be deleted after use, the Python language will release the resources occupied by the class. At this time, the Python interpreter will call a destructor method by default. The destructor method is automatically triggered when the object is released in memory. This method generally does not need to be defined, because python is a high-level language, and programmers do not need to care about the allocation and release of memory when using it. The call of the destructor method is automatically triggered by the interpreter when it performs garbage collection.
In a Python class, the syntax for manually adding a destructor method is as follows:

 def  __del__(self):
    代码块
c. Notes on construction methods and destructor methods:
  • In the method name of the constructor and the destructor, there should be an underscore at the beginning and end, and there should be no spaces in between.
  • In the Python language, if you do not manually create a constructor, the system will automatically add a constructor that only contains the self parameter for the class.
  • In the Python language, the destructor method can also be omitted, because Python has a garbage collector that can automatically handle memory management.

4. Use of self

It is stipulated in the Python class that the first parameter of the function is the instance object itself, and by convention, its name is written as self. Its function is equivalent to this in java, representing the object of the current class, and can call the properties and methods in the current class.

3) The three characteristics of object-oriented

1. Encapsulation

Encapsulation, as the name suggests, is to package something that you don’t want others to modify casually. Others can only see the appearance of the package and can only operate through the interface provided by the appearance, without knowing the internal principle and cannot directly modify the internal things. .
In an object-oriented programming language, encapsulation is to hide the properties that do not want to be modified by the outside world, and only expose the interface to the outside world. In this way, when using this class, these properties cannot be directly called in the form of "class object. property name". Instead, these hidden attributes can only be indirectly manipulated by unhidden class methods to achieve the purpose of controlling the access level of reading and modifying attributes in the program.
Variables and methods in Python classes are either public (similar to public attributes) or private (similar to private). The differences between these two attributes are as follows:

  • public: Class variables and class methods of public attributes can be accessed normally outside the class, inside the class, and in subclasses (details will be introduced later when we talk about inheritance features);
  • private: Class variables and class methods of private attributes can only be used inside the class, and cannot be used outside the class or subclasses.

Python does not provide modifiers such as public and private. In order to achieve class encapsulation, Python takes the following approach:

  • By default, variables and methods in Python classes are public (public), and there is no underscore (_) before their names;
  • If the names of variables and methods in a class begin with double underscores "__", the variable (method) is a private variable (private method), and its attributes are equivalent to private.

2. Inheritance

A major feature of object-oriented programming (OOP) languages ​​is "inheritance." In real life, children can inherit the inheritance of their parents. Object-oriented inheritance is similar to this, that is, a class can directly use the properties and methods of another class without redefining. The new class created by inheritance is called "subclass" or "derived class", and the inherited class is called "base class", "parent class" or "super class", generally called "parent class".
There are two types of inheritance in the Python language: single inheritance and multiple inheritance.

a. Single inheritance

Single inheritance means that a class can only have one parent class, that is, it can only inherit from one class, and cannot inherit multiple classes at the same time, but a parent class can have multiple subclasses at the same time.
Single inheritance is a commonly used type of inheritance. The basic grammatical format of single inheritance is as follows:

  class 子类名(父类名)
                      子类代码块

Structural diagram of single inheritance:
image.png

b. Multiple inheritance

Unlike the Java language, the Python language can implement multiple inheritance. For example: a working student, he is both a student and a worker, that is, he has both the attributes and methods of the student and the attributes and methods of the worker, so it can be said that he has two parent classes, let him inherit the student class at the same time And the worker class is enough, this is multiple inheritance. The basic grammatical format of multiple inheritance is as follows:

class 子类名(父类1,父类2……)
                      子类代码块

Structural diagram of multiple inheritance:
image.png

c. Overwrite and rewrite

In the inheritance relationship, the subclass automatically inherits the properties and methods of the parent class, but sometimes the properties and methods inherited by the subclass need to have their own names and implementation methods. At this time, the properties and methods of the parent class can be modified in the subclass Perform reassignment or rewrite. The reassignment of general properties is called overwriting, and the rewriting of methods is called rewriting. When overriding and overriding, note that the attribute names that the subclass needs to override must be exactly the same as the attribute names of the parent class, and the method names and parameter lists that the subclass needs to rewrite must be exactly the same as the method names and parameter lists of the parent class.

3. Polymorphism

Polymorphism (Polymorphism) literally means "multiple states". In object-oriented languages, polymorphism means that the same method name can be used to achieve different functions, that is to say, a method name can be used to call methods with different contents (functions). Python's polymorphism refers to: using instances without considering the instance type, that is to say, instances of different types have the same calling method, such as people, cats, dogs, etc., as long as they inherit Animal, they can call it directly The move() method.

  • The characteristics of polymorphism are:
  • Only care about whether the instance method of the object has the same name, not the type of the object;
  • Between the classes to which objects belong, the inheritance relationship is optional;
  • The benefits of polymorphism can increase the flexibility of external calls of the code, making the code more versatile and more compatible;
  • Polymorphism is the art of calling methods without affecting the internal design of the class.

4) Class attributes and class methods

Everything in the Python language is an object: class AAA: The defined class belongs to the class object, and the object created by obj1 = AAA() belongs to the instance object. An object created using a class is called an instance of the class, the action of creating an object is called instantiation, the properties of the object are called instance properties, and the methods invoked by the object are called instance methods. When the program is executed, each object has its own instance attributes, calls its own instance methods, and can access its own attributes and call its own methods through self. In Python, a class is a special object—a class object. When the program is running, the class will also be loaded into memory. There is only one copy of the class object in memory. Using a class can create many object instances, except for encapsulation In addition to the properties and methods of the instance, the class object can also have its own properties and methods, which are called class properties and class methods. You can access the properties of the class or call the methods of the class through the class name.

1. Class attributes

A class attribute is an attribute owned by a class. It is usually used to record the characteristics related to this class. The class attribute will not be used to record the characteristics of a specific object. Class attributes need to be explicitly defined in the class (located outside all methods in the class, and attributes defined inside methods are instance attributes), and can be shared by all instances of the class. The basic format for defining class attributes is as follows:

class 类名:
                类属性
                def 方法名():
                         实例属性

Class attributes can be accessed using either the class name or the instance name, but in general we advocate using the class name to access class attributes. The reasons are as follows:

  • When accessing class properties using the instance name, you may have unwanted results.
  • If the class attribute and the instance attribute have the same name, then only the class name can be used to access the class attribute, and if the instance name is used, the instance attribute is accessed.

2. Class methods

A class method is a method defined for a class object. Inside a class method, you can directly access class attributes or call other class methods. Its basic syntax is as follows:

class 类名:
                       @classmethod
                       def 类方法名(cls):
                                 方法体

Class methods need to be identified with the decorator @classmethod to tell the interpreter that this is a class method. The first parameter of the class method should be cls, which class calls the method, the cls in the method is the reference of which class, this parameter is similar to the first parameter of the instance method is self (you can use other names, But get used to using cls). Call the class method through the name of "class name. class method". You don't need to pass the cls parameter when calling the method. Inside the method, you can access the attributes of the class through "cls. attribute", or you can call other methods through "cls. method". class method. You can call a class method through the class name, or you can call a class method through the object name, and the two methods are the same.

Guess you like

Origin blog.csdn.net/xiaoyu070321/article/details/132298492
Recommended