Python study notes (twenty) - object-oriented

(1) The benefits of object-oriented

In daily life, a unified form is often used when recording data, so that the format of the data information will not be confused. Similarly, in the data organization in the program, recording only through variables will appear chaotic and inconsistent.

In the program, it is possible to design forms, produce forms, and fill in forms of organization just like in life.

1. Design the table in the program , we call it: design class ( class )

2. Print the production form in the program , we call it: create object

3. Fill in the form in the program , we call it: object attribute assignment

(2) Definition and use of classes

Syntax for creating a class:

 

class is a keyword, which means to define a class
The attributes of the class , that is, the variables defined in the class (member variables)

       The behavior of the class , that is, the function (member method) defined in the class 

 Syntax for creating a class object:

 

 (3) Member variables and member methods

 

It can be seen that in the class:

Not only attributes can be defined to record data
Functions can also be defined to record behavior

in:

The attributes (variables ) defined in the class , we call them: member variables
The behavior (function ) defined in the class , we call it: member method

(4)  Definition syntax of member methods

Defining member methods in a class is basically the same as defining functions, but there are still subtle differences:

As you can see, in the parameter list of the method definition, there is one: self keyword

The self keyword must be filled in when the member method is defined .

It is used to represent the meaning of the class object itself
When we use the class object to call the method, self will be automatically passed in by python
Inside the method, if you want to access the member variables of the class, you must use self

The self keyword, although it is in the parameter list, can be ignored when passing parameters.

like:

 

 It can be seen that when passing in parameters, self is transparent, so you can ignore it

(5)  Construction method

In the above code, assigning values ​​to the properties of the object needs to be done sequentially, which is a bit cumbersome. Is there a more efficient way that can be done in one line of code? Yes, you need to use the constructor: __init __()

Python classes can use: __init __() method, called constructor .

can be realised:

When creating a class object (constructing a class), it will be executed automatically.
When creating a class object (construction class), the incoming parameters are automatically passed to the __init__ method for use.

 Notice:

Construction method name:   __init__ , don't forget that there are 2 underscores before and after init
The constructor is also a member method, don't forget to provide in the parameter list: self
To define member variables in the constructor, you need to use the self keyword

(6) Several commonly used class built-in methods (magic methods)

The __init__ construction method above is one of the built-in methods of the Python class.

These built-in class methods each have their own special functions. We call these built-in methods: magic methods

There are many magic methods, here are a few common ones

__str__ string method

Method name: __str__        Return value: string        Content: define by yourself

When the class object needs to be converted to a string, the above result (memory address) will be output

The memory address does not have much effect, we can control the behavior of converting the class to a string through the __str__ method.

__lt__ less than sign comparison method

 Input parameter: other, another class object        Return value: True or False         • Content: self-defined

__lt__ method, can be completed at the same time: less than sign and greater than sign 2 comparisons

The magic method for comparing the greater -  than sign is: __gt__ , however, __lt__ is implemented , so __gt__ is not necessary

__le__ is less than or equal to the comparison symbol method

Input parameter: other, another class object         • Return value: True or False Content: self-defined

 __le__ can be used on: <= , >= two comparison operators.

The magic method of the >= symbol implementation is: __ge__ , however, __le__ is implemented , and __ge__ is not necessary

__eq__  comparison operator implementation method

Input parameter: other, another class object         • Return value: True or False         • Content: self-defined

If the __eq__ method is not implemented, objects can be compared, but the memory address is compared, that is: different objects == comparison must be False results.

After implementing the __eq__ method, you can decide whether two objects are equal according to your own ideas

 (7) Three major characteristics of object-oriented

Object-oriented programming is a programming idea supported by many programming languages.

A simple understanding is: create entities (objects) based on templates (classes), and use objects to complete functional development.

Object-oriented includes 3 main features:

ØPackage _
o Inheritance
Ø Polymorphism

(8) Encapsulation

Encapsulation means that the attributes and behaviors of real-world things are encapsulated into classes, described as: member variables and member methods , so as to complete the program's description of real-world things.

Things in the real world have attributes and behaviors. However, it does not mean that these attributes and behaviors are open to users.

Since real things have non-public attributes and behaviors, the classes mapped in the program as real things should also support them.

The class provides support in the form of private members .

Private member variables
private member methods

The way to define private members is very simple, just need:

Private member variables: variable names start with __ ( 2 underscores)
Private member methods: method names start with __ ( 2 underscores)

You can complete the private member settings

Private methods cannot be used directly by class objects        

              

A private variable cannot be assigned a value, nor can it get a value

 

Private members cannot be used by class objects, but can be used by other members.

 (9) inheritance

①Single inheritance

If we don't use inheritance, when we want to create a new class, we need to redefine variables and methods, which is cumbersome, as follows

And the use of inheritance can make the code more concise

Using the syntax shown in the figure below, single inheritance of classes can be accomplished.

Inheritance means: member variables and member methods (excluding private) will be inherited (copied) from the parent class

 ②Multiple inheritance

Python classes also support multiple inheritance, that is, a class can inherit multiple parent classes

 

 

 Multiple Inheritance Considerations

In multiple parent classes, if there are members with the same name, the inheritance order (from left to right) is the priority by default .

That is: the first inheritance is reserved, and the later inheritance is overwritten

 

③pass keyword

pass is a placeholder statement, used to ensure the integrity of the function (method) or class definition, meaning no content, empty

④ Copy

After the subclass inherits the member attributes and member methods of the parent class, if it is " unsatisfied " with it , it can be copied.

That is: just redefine the property or method with the same name in the subclass.

Once the parent class member is overwritten, when the class object calls the member, the overwritten new member will be called

If you need to use the members of the overridden parent class, you need a special calling method :

Method 1 :
Call parent class members

     Use member variables: parent class name . member variables

     Use member method: parent class name . member method (self)

Way 2 :
Use super() to call parent class members

     Use member variables: super(). Member variables

     Use member methods: super(). Member method ()

Only members with the same name of the parent class can be called inside the subclass, and the entity class object call of the subclass is called by subclass override by default

(10) Type annotations

Python introduced type annotations in version 3.5 to facilitate third-party tools such as static type checking tools and IDEs.

Type annotations: Provide data type annotations (explicit descriptions) where data interaction is involved in the code.

The main function:

Help third-party IDE tools (such as PyCharm ) perform type inference on code and assist in code hinting
Help developers type annotations on variables themselves

support:

Type annotations for variables
Type annotations for function (method) formal parameter lists and return values

Set type annotations for variables

method one:

Basic syntax:   variable : type

     

 

 

Notice:

Tuple type setting type detailed annotation, each element needs to be marked out
Dictionary type setting type detailed annotation, need 2 types, the first is key and the second is value
 Method Two:

In addition to using variable : type, this syntax is used for annotations, and type annotations can also be made in annotations .

Syntax:   # type: type

Generally, when the variable type cannot be seen directly, the type annotation of the variable will be added

Type Annotation Restrictions

The main functions of type annotations are:

Help third-party IDE tools (such as PyCharm ) perform type inference on code and assist in code hinting
Help developers themselves to type annotations on variables (remarks)

It does not really verify and judge the type.

That is, type annotations are only suggestive, not definitive

 

As shown in the code, no error will be reported.

②  Type annotations of functions (methods)

【1】Formal parameter annotation

as the picture shows:

When writing a function (method) and using the formal parameter data , the tool does not give any hints
When calling a function (method) and passing in parameters, the tool cannot prompt the parameter type

These are all because we did not annotate the formal parameters when we defined the function (method)

Parameter type annotation syntax for functions and methods:

【2】Return value annotation

At the same time, the return value of the function (method) can also add type annotations.

The syntax is as follows: Note that the symbol of the return value type annotation is used: ->

 ③Union type _

Using Union[type, ..., type] , you can define union type annotations

 Union joint type annotations can be used in variable annotations, function (method) formal parameters, and return value annotations.

(11) Polymorphism

Polymorphism refers to: multiple states, that is, when a certain behavior is completed, different objects will be used to obtain different states.

The same behavior (function), different objects are passed in, and different states are obtained

 abstract class (interface)

A class that contains abstract methods is called an abstract class. An abstract method means: a method ( pass ) that has no concrete implementation is called an abstract method

It is mostly used for top-level design (design standards), so that subclasses can implement it concretely.

It is also a soft constraint on subclasses, requiring subclasses to override (implement) some methods of the parent class

And use it in conjunction with polymorphism to obtain different working states.

 

 

Guess you like

Origin blog.csdn.net/laosao_66/article/details/131619403