Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Python object-oriented programming and what are its three Features

2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, I would like to share with you the relevant knowledge of python object-oriented programming and what the three features are. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.

Process-oriented programming: "process-oriented" (Procedure Oriented) is a process-centered programming idea. These are all about programming with the goal of what is happening, unlike object-oriented who is being affected. The obvious differences between object-oriented and object-oriented are encapsulation, inheritance and class.

Process-oriented programming is most easily accepted by beginners, which often uses a long piece of code to achieve the specified function. the idea of the development process is to organize the data and functions in the logical order in which they are executed, and the data and functions are considered separately.

Features: modular flow

Advantages: performance is higher than object-oriented, because class calls need to be instantiated, more expensive, more resource-consuming; single-chip microcomputer, embedded development, Linux/Unix and other general use of process-oriented development, performance is the most important factor.

Disadvantages: no object-oriented easy to maintain, easy to reuse, easy to expand

Functional programming: functional programming is also a way of programming, which regards computer operations as the calculation of functions. The most important foundation of functional programming language is lambda calculus (lambda calculus), and the functions of lambda calculus can accept functions as inputs (parameters) and outputs (return values).

Its main idea is to write the operation as a series of nested function calls as much as possible.

Python is not and unlikely to become a functional programming language, but it supports many valuable functional programming language builds. Others behave like functional programming mechanisms but cannot traditionally be thought of as the construction of functional programming languages.

Python built-in functions: filter (), map (), reduce (), max (), min ()

Object-oriented programming: object-oriented is a method of analyzing, designing and implementing software based on the concept of object (entity), which is based on the systematic way of thinking in which people understand the objective world. Through the object-oriented concept, the computer software system can correspond to the real world system one by one.

Object-oriented programming can bind data to functions and encapsulate them, so that programs can be developed more quickly and the rewriting process of repetitive code can be reduced.

Features: abstract encapsulation inheritance polymorphism

Advantages: easy to maintain, easy to reuse, easy to expand, because object-oriented has the characteristics of encapsulation, inheritance and polymorphism, we can design a low-coupling system, which makes the system more flexible and easier to maintain.

Disadvantages: lower performance than process-oriented

We can use examples in life to understand process-oriented and object-oriented, such as Gobang, the process-oriented design idea is the first step to analyze the problem: 1, start the game, 2, sunspot go first, 3, draw the picture, 4, judge whether to win or lose, 6, draw the picture, 7, judge whether to win or lose, 8, return to step 2, and output the final result. Implement each of the above steps in a different way.

If it is the object-oriented design idea to solve the problem. Object-oriented design is to solve problems from another way of thinking. The whole Gobang can be divided into 1, black and white, the behavior of the two sides is exactly the same, 2, the chessboard system, responsible for drawing the picture, 3, the rule system, responsible for judging such as fouls, winning or losing, and so on. The first kind of object (player object) is responsible for accepting user input and informing the second kind of object (chessboard object) of the change in the layout of the chessboard. when the chessboard object receives the change of the chess piece, it is responsible for displaying the change on the screen. at the same time, the third kind of object (rule system) is used to determine the chess game.

It is obvious that object-oriented divides problems by functions, not steps. Also drawing chess games, this behavior is scattered in many steps in process-oriented design, and different drawing versions are likely to appear, because designers usually make a variety of simplifications taking into account the actual situation. In the object-oriented design, the drawing can only appear in the chessboard object, thus ensuring the unity of the drawing.

Three characteristics of object-oriented programming

Before looking at the three major features of object-oriented programming, let's take a look at the difference between objects and classes.

Objects and classes

A Class is a reflection of an entity in the real or mental world in a computer. It encapsulates data and operations on that data. Class is actually a template for creating an instance.

An object (Object) is a variable with a class type. Classes and objects are the most basic concepts in object-oriented programming technology. And the object is a concrete example.

The method that defines the class:

Class class (): pass

So how do you convert a class to an object?

Instantiation refers to the process of creating objects with classes as instantiation in object-oriented programming. It is the process of concreting an abstract concept class to this kind of physical object. In the process of instantiation, it is generally determined by the class name object name = class name (parameter 1, parameter 2. Parameter n) composition.

The constructor method init is generally used after defining a class. Unlike other ordinary methods, the constructor method (also known as the magic method) is called immediately after an object is created. Automatically executes the contents of the constructor.

1. Package characteristic

Encapsulation, as the name implies, encapsulates the content in a certain place, and then invokes the content encapsulated somewhere later. Therefore, when using object-oriented encapsulation features, you need to:

Encapsulate the content somewhere

To call the encapsulated content from somewhere, the method is as follows:

The encapsulated content is called directly through the object: the object. Attribute name

The encapsulated content is called indirectly through self: self. Attribute name

The encapsulated content is called indirectly through self: self. Method name ()

For object-oriented encapsulation, it is to encapsulate the content into an object using construction methods, and then obtain the encapsulated content directly or indirectly through the object or self.

Specific examples are as follows:

# 1) Class definition class People: # constructor (magic method): automatically called and executed when an object is created; # self is essentially an instantiated object, e.g: xiaoming, xiaohong Def _ init__ (self, name, age, gender): # print ("creating object") # print (self) # is essentially an object # encapsulates the properties (name, age, gender) of the created object in the self (that is, the instantiated object) variable # variable defined in the class: attribute self.name = name self.age = age self.gender = gender # function defined in the class: method def eat (self): print ('% s eating.'% (self.name)) def sleep (self): # get the properties encapsulated by the object self (name, age) Gender) print ('% s sleep.'% (self.name)) # 2). Instantiation: implement the creation of the object through the class xiaoming = People ("Xiaoming", 20, 'male') # take out the attributes encapsulated by the object self/xiaoming (name, age, gender); print (xiaoming.name) xiaoming.eat () xiaoming.sleep () xiaohong = People ("Xiao Hong", 20, 'female') print (xiaohong.name) xiaohong.eat () xiaohong.sleep () 2, inheritance feature 1) inheritance

Inheritance describes the ownership relationship between things. When we define a class, we can inherit from an existing class. The new class is called subclass, extended class (Subclass), and the inherited class is called base class, parent class or superclass (Baseclass, Superclass).

Question 1: how to implement inheritance?

When a child class inherits, when defining a class, the parenthesis () is the name of the parent class, for example: class son (father): where father is the parent class of son.

Question 2: what is the working mechanism of inheritance?

The properties and methods of the parent class are inherited to the subclass. The example is as follows: if the subclass does not define an init method and the parent class does, then this method is inherited when the subclass inherits the parent class, so as long as the object is created, the inherited init method is executed by default.

Override the parent method: that is, if there is a method with the same name as the parent class in the subclass, then the method in the subclass will override the method with the same name in the parent class, thus realizing the rewriting of the parent method.

Call the method of the parent class:

In subclasses, use the parent class name directly. Method name of the parent class ()

Super () method: python2.2+ function, format: super (subclass name, self). The method name of the parent class () (recommended)

2) multiple inheritance

Multiple inheritance, that is, subclasses have multiple parent classes and have their characteristics.

The difference between new classes and classical classes:

In Python 2 and previous versions, classes derived from any built-in type were "new classes" and acquired the features of all "new classes"; conversely, classes that were not derived from any built-in types were called "classical classes".

New class:

Class class name (object):

Pass

Classic class:

Class class name:

Pass

The distinction between "new classes" and "classic classes" no longer exists after Python 3, and after Python 3.x, because all classes are derived from the built-in type object (even if there is no inheritance object type shown), that is, all classes are "new classes".

The most obvious difference between them is the order in which they inherit the search, namely:

Classic class multi-inheritance search order (depth-first algorithm): first go deep into the left side of the inheritance tree, and then return, and start looking on the right side.

New class multi-inheritance search order (breadth-first algorithm): first look in the horizontal direction, and then look up.

The figure is as follows:

Specific examples are as follows:

# python2: # Classical Class: class Father: # New Class: class Father (object): # python3:# all are new classes # New Class: breadth first # Classical Class: depth first class D: a = 'd'class B (D): passclass C (D): a =' c'class A (B, C): passobj = A () print (obj.a)

The running result is c, which shows that it is the result of breadth-first search.

3) Private attributes and private methods

By default, attributes are "public" in Python, and most OO (object-oriented) languages provide "access control characters" to restrict access to member functions.

In Python, if the variable name of an instance starts with _ _ (double underscore), it becomes a private variable / property (private). If the function name of an instance starts with _ _, it becomes a private function / method (private) that can only be accessed internally but not externally.

So must private properties not be externally accessible?

The python2 version cannot access the attribute name directly because the Python interpreter has changed the attribute name to the _ class name attribute name, so you can still access the attribute name through the _ class name attribute name. However, different versions of the Python interpreter may change the property name to a different variable name, so it is not recommended to use this method to access private properties.

Advantages of private properties and methods:

It ensures that the external code can not modify the internal state of the object at will, so that the code is more robust through the protection of access restrictions.

What if you want to allow external code to modify properties? You can add special property setting methods to the class. Why go to so much trouble? Because in the method, you can check the parameters to avoid passing in invalid parameters.

Specific examples are as follows:

Class Student (object): _ _ country = 'china' def _ _ init__ (self, name, age, score): self.name = name # Age and score are private attributes self.__age = age self.__score = score # private methods can only be executed within the class Def _ modify_score (self, scores): self.__score = scores print (self.__score) def set_age (self, age): if 0

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report