Concise python3 tutorial 13. Object-Oriented Programming

Source: Internet
Author: User

Introduction

(Note: Oop stands for Object-Oriented Programming, and OO stands for object-oriented, which will be abbreviated later)

So far, all programs we have written are created around functions, namely the statement block for manipulating data. This is called process-oriented programming.

In addition, there is another way to organize programs, which combines data and functions into things called objects. This is called oop.

Most of the time you can use procedural programming, but when writing large programs or problems tends to be solved in an OO way, you can also use OOP technology.

Classes and objects are two important features of OOP. Class is used to create a new type, and the object is a class instance. This is like creating int-type variables. These variables are instances (objects) of the int class)

 

For static language programmers, please note

Note that in Python, integers are treated as objects (INT class objects ).

This is different from C ++ and Java (versions earlier than 1.5). The integers in these are of the original local type. For details, seeHelp (INT).

C # and Java 1.5 programmers will find that this is similar to boxing and unboxing.

 

Objects can store data using the variables that belong to this object. Variables that belong to objects or classes are called fields ).

Objects can also use functions of classes to implement the required functions. These functions are called methods ).

These terms are important because they help us distinguish independent functions and variables from functions and variables that belong to Classes or objects.

Fields and methods are collectively referred to as class attributes.

Fields are classified into two types-they can belong to both the instance/Object of the class and the class itself. The two are called instance variables and class variables respectively.

A class uses keywordsClassCreate. Fields and methods are listed in the class indent block.

 

Self

There is only one special difference between a class method and a common function-an additional parameter must be added to the class method, and it must be at the position of the first parameter,

However, when calling a class method, do not pass the value for this additional parameter. python will automatically perform this operation. This special variable references the object itself, which is namedSelf.

Although you can name this parameter at will, I strongly recommend that you useSelf-Other names frown.

There are many benefits to using a standard name-any reader of your code will immediately understand what it represents, and even professional ide will help you better when you use a standard name.

 

WriteC ++/Java/C #Programmer

In python, self is equivalent to the this pointer in C ++ and this reference in Java/C #.

 

You must be confused about how Python assigns values to self. Why don't you manually assign values? For example, we can make things clearer.

Suppose you haveMyclassClass and its instanceMyobject. When you call the method of this objectMyobject. Method (arg1, arg2),

Python automatically converts itMyobject. Method (myobject, arg1, arg2)-This is the inside story about self.

This also means that if you have a method without parameters, you still needSelfReal parameters.

 

Class

The following example can be the simplest class.

#! /Usr/bin/Python

# Filename: simplestclass. py

Class person:

Pass # empty statement Block

P = person ()

Print (P)

Output:

$ Python simplestclass. py

<__ Main _. Person object at 0x019f85f0>

How code works:

We useClassStatement and a class name create a new class, followed by a statement block that defines the indentation of the class body. In this examplePassA statement represents an empty statement block.

Next, we will create the object/instance of this class. The method is the class name followed by a pair of parentheses (we will learn more about the instance in the next section ).

To verify the variable type, we simply print it. It tells us that we havePersonClass.

Note that the computer memory address for storing this object is printed. The address value may be different in your computer, because Python stores the object as long as it finds the available space.

 

Object Method

We have discussed that objects/classes can have methods similar to functions, but these functions must be added with additionalSelfVariable. Now let's look at an example.

#! /Usr/bin/Python

# Filename: method. py

Class person:

Def sayhi (Self ):

Print ('hello, how are you? ')

P = person ()

P. sayhi ()

# In this short example, you can also write person (). sayhi ()

Output:

$ Python method. py

Hello, how are you?

How code works:

Here we useSelf, Note the MethodSayhiAlthough no parameters are required, you still need to write them in the function.Self.

 

_ Init __Method

In Python classes, many method names have special meanings. Let's take a look._ Init __Method.

_ Init __The method is executed immediately when the class object is instantiated. This method is used to initialize objects. In addition, pay attention to the prefix and suffix of the double-underline in the method name.

Example:

#! /Usr/bin/Python

# Filename: class_init.py

Class person:

Def _ init _ (self, name ):

Self. Name = Name

Def sayhi (Self ):

Print ('hello, my name is ', self. Name)

P = person ('swaroop ')

P. sayhi ()

# In this short example, you can also write person (). sayhi ()

Output:

$ Python class_init.py

Hello, my name is swaroop

Example:

Here we defineNameParameter_ Init __Method (Except ordinary self ).

Then we created anotherName. Note that they are two different variables, although both are called 'name '. Point Numbers allow us to separate them.

The point is that we have not explicitly called_ Int __Instead, specify the real parameters in parentheses after the class name when creating the class instance. This is_ Init __.

After initialization, we can useSelf. NameField, MethodSayhiThis is demonstrated.

 

Class and object variable

We have discussed the functions (methods) of classes and objects. Now we will learn the data section.

Data is a field, but a common variable bound to the namespace of the class and object. This means that these names are valid only in the context of their classes and objects. This is why they are called namespaces.

There are two types of fields-class variables and object variables, which are differentiated based on whether the owner is a class or an object.

Class objects are shared-they can be accessed by all instances of a class. That is, only one copy of a class object exists in the class, and any modification to the object will be reflected on all objects.

Each Independent Class Object/instance has its own object variables. In this way, each object has its own field copy, that is, these fields are not shared, and the object variables of the same name in different objects are not associated with each other.

For example, it is easier to understand:

#! /Usr/bin/Python

# Filename: objvar. py

 

Class ROBOT:

'''Represents a robot, with a name .'''

# A Class variable is used to record the number of robots

Population = 0

 

Def _ init _ (self, name ):

'''Initializes the data .'''

Self. Name = Name

Print ('(initializing {0})'. Format (self. Name ))

 

# When this person is created, the robot

# Adds to the population

Robot. Population + = 1

Def _ del _ (Self ):

''' I am dying .'''

Print ('{0} is being destroyed! '. Format (self. Name ))

 

Robot. Population-= 1

 

If robot. Population = 0:

Print ('{0} was the last one.'. Format (self. Name ))

Else:

Print ('there are still {0: d} robots

Working. '. Format (robot. Population ))

 

Def sayhi (Self ):

'''Greeting by the robot.

 

Yeah, they can do that .'''

Print ('greetings, my masters call me {0}. '. Format (self. Name ))

Def howmany ():

'''Prints the current population .'''

Print ('we have {0: d} robots. '. Format (robot. Population ))

Howmethod = staticmethod (howmethod)

 

Droid1 = Robot ('r2-D2 ')

Droid1.sayhi ()

Robot. Howmany ()

 

Droid2 = Robot ('C-3po ')

Droid2.sayhi ()

Robot. Howmany ()

 

Print ("/nrobots can do some work here./N ")

Print ("robots have finished their work. So let's destroy them .")

Del droid1

Del droid2

Robot. Howmany ()

Output:

(Initializing R2-D2)

Greetings, my masters call me R2-D2.

We have 1 robots.

(Initializing C-3PO)

Greetings, my masters call me C-3PO.

We have 2 robots.

Robots can do some work here.

Robots have finished their work. So let's destroy them.

R2-D2 is being destroyed!

There are still 1 robots working.

C-3PO is being destroyed!

C-3PO was the last one.

We have 0 robots.

How code works:

This example is long but helpful in demonstrating the nature of classes and object variables.

PopulationBelongRobotSo it is a class variable. VariableNameBelongs to the object (using self assignment), so it is an object variable.

Therefore, we useRobot. PopulationReference class variablesPopulatinInsteadSelf. Population.. The object variable is referenced in the method.NameUseSelf. NameSyntax.

Remember the simple differences between this class variable and the class object. Also note that object variables will hide class variables with the same name!

HowmanyIt is actually a class method rather than an object. This means we can define itClassmethodIt can also be definedStaticmethod,

It depends on whether we need to know which class we are part. Because we do not need similar information, we use staticmethod.

In addition, we can use the decorators to achieve the same effect:

@ Staticmethod

Def howmany ():

'''Prints the current population .'''

Print ('we have {0: d} robots. '. Format (robot. Population ))

The modifier can be imagined as a shortcut to call an explicit statement, as shown in this example.

Observe the _ init _ method, which is used to initialize a robot instance with a specified name. It accumulates 1 for population internally because we have added another robot.

At the same time, observe self. Name. Its value is specific to each object, which also points out the essence of class objects.

Remember, you can only use self to reference the variables and methods of the same object. This is called attribute reference.

In this example, we also use document strings in classes and methods. We can useRobot. _ Doc __AndRobot. sayhi. _ Doc __Document strings of the category class and method respectively.

Just like_ Init __Method. There is another special method._ Del __When the object fails, it will be called.

If an object is suspended, the space occupied by the object is returned to the system for reuse.

In _ del _, we simply subtract 1 from robot. Population.

When an object is no longer used, the _ del _ method can be executed, but it cannot be guaranteed when it is executed.

If you want to execute it explicitly, you must useDelStatement, as in this example. (Note: In this example, the reference count of the del object is reduced to 0 ).

 

C ++/Java/C #Attention for programmers

All class members (including data members) in Python are public, and all methods are virtual.

Only one exception: if the data member you are using has a double-underline prefix, for example_ PrivatevarPython uses the name obfuscation mechanism to effectively use it as a private variable.

There is also a convention that any variable used only within a class or object should be prefixed with a single underline, and other variables are public and can be used by other classes/variables.

Remember that this is just a convention rather than a force (except for the double-underline prefix ).

 

Inheritance

The main benefit of OOP is code reuse, and one of the methods to achieve this goal is to use the inheritance mechanism. It is best to think of inheritance as the relationship between types and subtypes between classes.

Suppose you want to write a program to track the students and students in the University. Teachers and students share many common features, such as names, ages, and addresses.

They also have different characteristics, such as teachers' salaries, course holidays, and students' scores and tuition fees.

You can create two independent classes for the teachers and students and process them separately, but adding a common feature means that both classes will increase. Soon this design method will become bulky and bloated.

A better way is to createSchoolmemberAnd then let the teachers and students inherit itSchoolmemberChild type. Then add their own proprietary features.

This method has many advantages. Any function we add or modify for schoolmember is automatically reflected in its child type.

For example, you can add an idcard field for teachers and students, simply adding it to schoolmember. However, changes in the Child type do not affect other child types.

Another benefit is that if you can reference a teacher or student object as a schoolmember object, this is useful for counting the number of students in a school.

This is called polymorphism. In any case where the parent type is required, its child type can be replaced with the parent type, that is, the object can be used as an instance of the parent class.

In addition, we can reuse the parent class code without repeating the code in different classes, but we have to repeat it when using the independent class we discussed earlier.

In this example, the schoolmember class is called a base class or a superclass.TeacherAndStudentClass is called a derived class or a subclass.

Now let's take a look at this example.

#! /Usr/bin/Python

# Filename: Inherit. py

Class schoolmember:

'''Represents any school member .'''

Def _ init _ (self, name, age ):

Self. Name = Name

Self. Age = Age

Print ('(initialized schoolmember: {0})'. Format (self. Name ))

Def tell (Self ):

'''Tell my details .'''

Print ('name: "{0}" Age: "{1}" '. Format (self. Name, self. Age), end = "")

 

Class teacher (schoolmember ):

'''Represents a teacher .'''

Def _ init _ (self, name, age, salary ):

Schoolmember. _ init _ (self, name, age)

Self. Salary = salary

Print ('(initialized Teacher: {0})'. Format (self. Name ))

Def tell (Self ):

Schoolmember. Tell (Self)

Print ('salary: "{0: d}" '. Format (self. Salary ))

Class student (schoolmember ):

'''Represents a student .'''

Def _ init _ (self, name, age, marks ):

Schoolmember. _ init _ (self, name, age)

Self. Marks = marks

Print ('(initialized Student: {0})'. Format (self. Name ))

Def tell (Self ):

Schoolmember. Tell (Self)

Print ('Marks: "{0: d}" '. Format (self. Marks ))

T = teacher ('Mrs. shrividya', 40,300 00)

S = student ('swaroop ', 25, 75)

Print () # print an empty line

Members = [t, s]

For member in members:

Member. Tell () # Work on both teacher and student

Output:

$ Python inherit. py

(Initialized schoolmember: Mrs. shrividya)

(Initialized Teacher: Mrs. shrividya)

(Initialized schoolmember: swaroop)

(Initialized Student: swaroop)

Name: "mrs. shrividya" Age: "40" Salary: "30000"

Name: "swaroop" Age: "25" marks: "75"

Example:

To use inheritance, we specify the base class name in a tuple after the class name defined by the class.

Then we noticed thatSelfVariables are used as parameters to call_ Init __Method to initialize the base class of the object.

Keeping this in mind is very important-Python does not automatically call the constructors of the base class, and you must explicitly call it yourself.

We also noticed that we can call the base class method by adding the class name prefix, and then transmit the self variable and any other real parameters for it.

Note that when we use the schoolmember classTellMethod, you canTeacherOrStudentAsSchoolmember.

At the same time, it should be noted that the program calls subtypes.TellMethod 2 is notSchoolmemberClassTellMethod.

One idea of understanding this mechanism is that python always finds the called method in the actual type. This is the case in this example.

If Python does not find the called method, it searches for the base class one by one. The query sequence is determined by the base class sequence specified in the tuples when the class is defined.

Another term is explained. If a class inherits multiple base classes, it is called multiple inheritance.

 

Summary

We have studied all aspects of classes and objects, as well as various terms related to them. We also see the advantages and traps of OOP.

Python is a highly OO language. Understanding these concepts carefully will be of great benefit to you.

Next, we will learn how to process input/output and file access in Python.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.