Home  >  Article  >  Backend Development  >  Explain the object-oriented core foundation of Python

Explain the object-oriented core foundation of Python

coldplay.xixi
coldplay.xixiforward
2020-12-14 17:40:462923browse

python video tutorialThe column introduces the core basic object-oriented

Explain the object-oriented core foundation of Python

##Related free learning recommendations:

python video tutorial

1. Introduction to object-oriented

Python from It was designed as an object-oriented language from the beginning, and because of this, it is easy to create classes and objects in Python. If you have not been exposed to object-oriented programming languages ​​before, you may need to first understand some basic features of object-oriented languages ​​and form a basic object-oriented concept in your mind. This will help you learn Python more easily. Object-Oriented Programming.

• Python is an object-oriented programming language

• The so-called object-oriented language simply understands that all operations in the language are performed through objects

Process-oriented • Process-oriented means to decompose our program into steps one by one, and complete the program by abstracting each step
• This writing method is often only suitable for one function , if you want to implement other functions, the reusability is often relatively low
• This programming method symbolizes human thinking and is easier to write
• 1. Mom puts on clothes and shoes to go out
• 2. Mom Ride an electric scooter
• 3. Mom goes to the supermarket and puts down the scooter
• 4. Mom buys watermelon
• 5. Mom checks out
• 6. Mom rides an electric scooter home
• 7. The child eats watermelon when you get home

Object-oriented programming language focuses on the object, not the process. For object-oriented everything is an object • The above method can be used by the child’s mother to Children buy melons to solve the problem
• The object-oriented programming idea is to save all functions into corresponding objects. If you want to use a certain function, just find the corresponding object directly
• This coding method is easier to read , and easy to maintain and reuse. However, the writing process does not conform to conventional thinking, and writing is relatively troublesome

  • Basic features of object-oriented
    Class: Used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. Objects are instances of classes.
  • Class variables: Class variables are public throughout the instantiated object. Class variables are defined in the class and outside the function body. Class variables are generally not used as instance variables.
  • Data attributes: class variables or instance variables, used to process data related to classes and their instance objects.
  • Method rewriting: If the method inherited from the parent class cannot meet the needs of the subclass, it can be rewritten. This process is called method override, also known as method rewriting.
  • Local variables: Variables defined in methods only act on the class of the current instance.
  • Instance variables: In the declaration of a class, attributes are represented by variables. Such variables are called instance variables and are declared inside the class declaration but outside other member methods of the class.
  • Inheritance: That is, a derived class inherits the fields and methods of the base class. Inheritance also allows an object of a derived class to be treated as a base class object. For example, there is such a design: an object of type Dog is derived from the Animal class, which simulates the "is-a" relationship (for example, Dog is an Animal).
  • Instantiation: Create an instance of a class, a specific object of the class.
  • Object: Data structure instance defined through a class. Objects include two data members (class variables and instance variables) and methods.
The idea of ​​Object-oriented Programming (OOP) programming is mainly designed for large-scale software. Object-oriented programming encapsulates data and methods related to operating data into objects, and organizes code and data in a way that is closer to human thinking, making the program more scalable and readable, thus greatly improving programming efficiency.

 
Python fully adopts object-oriented thinking and is a truly object-oriented programming language. It fully supports basic object-oriented functions, such as inheritance, polymorphism, encapsulation, etc.
In Python, everything is an object. For example, data types, functions, etc. are all objects.

  • Python supports multiple programming paradigms such as process-oriented, object-oriented, and functional programming. Differences between object-oriented and process-oriented:

Similarities: They are both ways of thinking about solving problems and ways of organizing code
Difference:
Procedure Oriented thinking: Process-oriented programming pays more attention to the "logical flow of the program" and is a kind of "executor" "Thinking, suitable for writing small-scale programs.
Object-oriented (Object Oriented) thinking: Object-oriented pays more attention to the "relationship between objects in the software", which is more in line with human thinking mode and is a " Designer's thinking is suitable for writing large-scale programs. Object-oriented can help us grasp and analyze the entire system from a macro perspective.
However, the micro-operations specific to the implementation part (that is, each method) still need to be handled with a process-oriented approach. Process-oriented and object-oriented are complementary to each other, and object-oriented cannot be separated from process-oriented.
Object-oriented thinking method When encountering complex problems, first look for nouns from the problem (more process-oriented, look for verbs), then determine which of these nouns can be used as classes, and then determine according to the needs of the problem Class attributes and methods determine the relationship between classes.

2. Class

  • Create class
  • We are currently learning Python’s built-in objects, but not all built-in objects can meet our needs, so we often need to customize some objects during development
  • The List item class is simply understood as Equivalent to a drawing, in program summary we need to create objects based on classes.
    A class is a drawing of an object
  • We also call an object an instance of a class
  • If multiple objects are created through a class, we call these objects a class of objects
  • A class is also an object. A class is an object used to create objects.
  • You can add variables to the object. The variables in the object are called attributes. Syntax: object.Attribute name = attribute value
class MyClass():
    pass

Class is abstract, also known as "object template". We need to create an instance object of the class through the class template, and then we can use the functions defined by the class.
In Python, Python objects include several parts:

Explain the object-oriented core foundation of Python

  • Object instantiation
mc = MyClass()mc1 = MyClass()mc2 = MyClass()mc3 = MyClass()

So, we need to define the constructor init() method, which will assign the properties of the object to the object we define. The constructor method is used to perform "initialization of the instance object", that is, after the object is created, the relevant properties of the current object are initialized and there is no return value.

init() The key points are as follows:

The name is fixed and must be: init()
The first parameter is fixed and must be: self. self refers to the instance object just created.
The constructor is usually used to initialize the instance attributes of the instance object. For example, in Example 1, the instance attributes are initialized: name and sound
The constructor is called through the "class name (parameter list)". After the call, the created object is returned to the corresponding variable. For example: cat = Animal('Little Flower','Meow Meow')
__init __() method: Initialize the created object. Initialization refers to: "Assigning values ​​to instance attributes"
__new __() method: Used to create objects, but we generally do not need to redefine this method.
If we do not define the __init__ method, the system will provide a default __init__ method. If we define the __init__ method with parameters, the system does not create a default __init__ method.
Note:
Self in Python is equivalent to the self pointer in C, and the this keyword in JAVA and C#. In Python, self must be the first parameter of the constructor, and the name can be modified arbitrarily. But generally follow the convention and call it self.
3. Definition of class

• Classes and objects are abstractions of things in real life
• Things contain two parts
• 1. Data (attribute)
• 2. Behavior (method)
• Call method object.Method name ()
• The difference between convenience call and function call: if it is a function call, there are several formal parameters when calling , several actual parameters will be passed. If it is a method call, one parameter is passed by default, so the method must have at least one formal parameter
• In the class code block, we can define variables and functions
• The variables will become public properties of the class instance, all All instances of this class can be accessed in the form of object.property name
• The function will become a public method of this class instance, and all instances of this class can be accessed in the form of object.method name

class Person():
    name = '奥特曼'
    def speak(w):
        print('我能说话')a = Person()b = Person()a.name = '葫芦娃'print(a.name)print(b.name)print(a.speak())print(b.speak())

4. Parameter self

  • 属性和方法

• 类中定义的属性和方法都是公共的,任何该类实例都可以访问
• 属性和方法的查找流程
• 当我们调用一个对象的属性时,解析器会现在当前的对象中寻找是否还有该属性,如果有,则直接返回当前的对象的属性值。如果没有,则去当前对象的类对象中去寻找,如果有则返回类对象的属性值。如果没有就报错
• 类对象和实例对象中都可以保存属性(方法)
• 如果这个属性(方法)是所以的实例共享的,则应该将其保存到类对象中
• 如果这个属性(方法)是摸个实例独有的。则应该保存到实例对象中
• 一般情况下,属性保存到实例对象中 而方法需要保存到类对象中

  • self

方法是从属于实例对象的方法。实例方法的定义格式如下:
 
    def 方法名(self ,[形参列表]):
      函数体

方法的调用格式如下:
    对象.方法名([实参列表]) 要点:

定义实例方法时,第一个参数必须为 self。和前面一样,self 指当前的实例对象。 调用实例方法时,不需要也不能给 self
传参。self 由解释器自动传参 函数和方法的区别

都是用来完成一个功能的语句块,本质一样。 方法调用时,通过对象来调用。方法从属于特定实例对象,普通函数没有这个特点。
直观上看,方法定义时需要传递 self,函数不需要。 实例对象的方法调用本质: alt

类中其他操作:

dir(obj)可以获得对象的所有属性、方法 obj.dict 对象的属性字典 pass 空语句,相当于占位符。
isinstance(对象,类型) 判断“对象”是不是“指定类型”。

class Person():

    def speak(self):
        print('你好我是%s' % self.name)

    def read(self):
        passa = Person()b = Person()a.name = '葫芦娃'b.name = '奥特曼'a.speak()b.speak()结果:
C:\Users\giser\AppData\Local\Programs\Python\Python37\python.exe D:/pycharm/pythonbasic/day09.py
你好我是葫芦娃
你好我是奥特曼

Process finished with exit code 0

                 

The above is the detailed content of Explain the object-oriented core foundation of Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete