Getting started with Python(16)

Getting started with Python (16/18)
**Section 16 **Object Oriented Programming

Hello everyone, so far, the python code we have written has a basic feature, which is to design programs and process data around functions according to needs. Even when facing relatively complex problems, solutions such as functions, modules, and packages can help us solve program architecture and code reuse problems. However, this programming method is still called process-oriented programming.

To put it simply, it is essentially a linear programming method. Although the uniqueness of python is enough to support its process-oriented programming, it will still be popular, and it can handle many problems with ease. However, compared to the object-oriented programming methods of other high-level languages, the process-oriented programming methods must have certain limitations.

So, today, let’s talk about Python object-oriented programming.

1、 The cornerstone of object-oriented programming: classes and instances

Classes and instances are the cornerstone of object-oriented programming. A class (Class) can create a new type (Type), where the object (Object) is the instance of the class (Instance).

**This more abstract concept, we can understand it like this, for example: **

2、 Class fields, methods, attributes

Classes can include Field (Field) and Method (Method).

In python, we can simply understand these concepts like this:

**Field, ** is the variable belonging to the class.

**Method, ** is a function belonging to the class.

Regarding the field, it has two types:

(1) The fields belonging to the instance (object) of the class are called Instance Variables;

(2) The fields subordinate to a certain class itself are called Class Variables.

Regarding the method, it has a special parameter self

The difference with ordinary functions: In addition to belonging to a certain class, a special parameter self needs to be added at the beginning of its parameter list, but you don't need to assign a value to this parameter when calling this method, Python will provide it for it.

In fact, when you call a method of a class, Python will automatically convert the self parameter to myobject, so you don't need to assign a value to it. This also means that if the method in your class does not plan to have parameters, you still have to add a self parameter to it.

**PS: **self in Python is equivalent to this pointer in C++, and this reference in Java and C#.

3、 Class creation

A class can be created through the class keyword.

The name of the class followed by a pair of brackets creates an instance of the class.

Next is an indented block of statements, representing the main body of this class.

**Example 16_1: ** In this example, we created an empty code block using the pass statement.

The running result shows: The ** main ** module of the myclass class has an instance MyClassObject, and shows the address where it stores the object in memory. Of course, the addresses you see should not be the same, because Python will store objects in any space it finds.

4、 Method creation

A class definition of a method (Method) is actually very simple, just like defining a function, the only difference is that its method also has an additional self parameter.

Example 16_2

Here we can see the existence of self. Please note that calling say_hi() does not originally require parameters, but we still need to provide the self parameter in the method definition.

5、__ init__ method

This method with double underscores before and after is a special method built in python.

Here we come to understand what is the special significance of the init method?

**__ The init__ method will run immediately when its class is instantiated (Instantiated). This method can initialize (Initialization) any target object you want to operate. **

Here you should pay attention to the double underscore added before and after init.

**Code analysis: **

(1). In this example, we define two name variables, but they are not the same and will not cause confusion. Because the dot in self.name means that its "name" is part of the "self" object, and the other name is a purely local variable.

(2) The instance of the MyClass class calls the say_hi() method, but it does not explicitly call the init() method, but it has already run. This is what makes this method special.

6、 Class variables and instance variables

Both fields and methods are attributes of the class.

We already know that methods implement the functions of a class. What about fields? **The field is used to store the data of the class. **

As a form of data, fields are actually ordinary variables bound to the namespace of the class and object (ie, the instance of the class). This means that the fields of the classes we define are only valid where these classes and objects exist (called "context"). To simplify it a bit more: Fields are actually ordinary variables bound to the class's namespace, and are only valid where these classes exist.

Two types of fields-class variables and instance variables.

Class Variables are Shared-they can be accessed (used) by all instances of the class. There is only one copy of this type of variable. When any object changes the class variable, the changes will be reflected in all other instances.

Instance variable (Object variable) is owned by each independent instance (object) of the class. In this case, each object has its own independent field, that is, they will not be shared, nor will they be associated in any way with fields of the same name in other different instances.

**Code analysis: **

(1) A class variable x is defined, which will be valid in all instances of the class. Note: The pre-class name is required when using it, such as MyClass.x.

(2) In method one, we also deliberately defined a local variable with the same name: x=-1. Please note that it does not therefore affect the value of x in Method 2.

7、 Class inheritance

A significant feature (and also a major advantage) of object-oriented programming is the reuse of code (Reuse), and one of the ways to achieve reuse is inheritance.

**Let's talk about an example of inheritance. The design requirements are: **Suppose an application involves university teachers and students. Some of these characteristics are shared by them, such as name, age, address. Other features, such as teachers’ salaries, courses, vacations, and students’ grades and tuition, are independently owned.

In the solution, you can create two "independent and cumbersome" classes for them to process information.

But there is a better way, is to create a public class called SchoolMember, and then create two subclasses: teacher (Teacher) subclass and student (Student) subclass, and let it inherit the SchoolMember class. Then, add some necessary unique characteristics to these subtypes.

Parent class**: **SchoolMember, also known as Base Class or Superclass.

**Subclasses: **Teacher and Student classes will be called Derived Classes or Subclasses.

**(1), first build a school class: **SchoolMember, namely: parent class (base class)

**(2) Create two more sub-categories: **Teacher and Student.

Please note: they declare the parent class through parentheses after the class name.

(3) Call the subclass

**# Code execution, output: **

( Initialized SchoolMember: Teacher Zhang)

( Initialized Teacher: Teacher Zhang)

( Initialized SchoolMember: Xiao Ming)

( Initialized Student: Xiao Ming)

Name: "Mr. Zhang" Age: "40" Salary: "30000"

Name:"小明" Age:"25" Marks: "75"

8、 Several important features of class and class inheritance

(1) The class inherits properties (fields and methods) from the base class

In practice, we can call the method of the base class by prefixing the method name in the subclass with the base class name, and then passing in self and other variables.

For example, in the Teacher and Student subclasses, we can directly use the method in the base class: SchoolMember.tell(self)

(2) The instance will inherit the attributes (fields and methods) of all readable classes (subclass and parent class)

In the case, when we use the tell method of the SchoolMember class, you will find that the tell method of the subtype is called instead of the tell method of SchoolMember. This is because Python always looks for methods from the type of the current instance. If it cannot find it, it will continue to search in the base class to which the class belongs.

**(3) If the init method is defined in the subclass, it will be called first. If the init method of the base class needs to be called at this time, it needs to be called explicitly. Unless the init method is not defined in the subclass, then the init method of the class will be executed automatically. **

For example, if we define the init method in the Teacher and Student subclasses, Python will not automatically call the constructor of the base class SchoolMember, and must call it explicitly. On the contrary, if we do not define the init method in the subclass, Python will automatically call the method of the base class.

**(4) Modify any function of the parent class, it will be automatically reflected in the child class. On the contrary, the modification of sub-categories will not affect other sub-categories. **

For example, in the case, you can add a new ID card field for all teachers and students by simply operating on the SchoolMember class.

summary

Python is highly object-oriented. In the long run, you can't just do small applications forever. Understanding these concepts will help you a lot.

Preview

In the next lesson, we will learn how to process input and output, and how to access files in Python, which is also an extremely important and widely used knowledge point in Python.

Recommended Posts

Getting started with Python(18)
Getting started with Python(9)
Getting started with Python(8)
Getting started with Python(4)
Getting started with Python (2)
Getting started with python-1
Getting started with Python(14)
Getting started with Python(7)
Getting started with Python(10)
Getting started with Python(11)
Getting started with Python(6)
Getting started with Python(3)
Getting started with Python(12)
Getting started with Python(5)
Getting started with Python (18+)
Getting started with Python(13)
Getting started with Python(16)
Getting started with Numpy in Python
Getting started with Ubuntu
Getting Started with Python-4: Classes and Objects
Getting started with python-2: functions and dictionaries
04. Conditional Statements for Getting Started with Python
Getting started python learning steps
How to get started quickly with Python
python requests.get with header
Play WeChat with Python
Web Scraping with Python
Implementing student management system with python
Centos6.7 comes with python upgrade to
Played with stocks and learned Python
Gray-level co-occurrence matrix (with python code)
Speed up Python code with Cython
How to make a globe with Python
Automatically generate data analysis report with Python
Create dynamic color QR code with Python
Python | Quickly test your Python code with Hypothesis