So far, in our programs, we have designed programs based on the function or statement block of operation data. This is called process-oriented
Programming. There is also a way to combine data and functions and wrap up the organizational program with something called an object. This method is called object-oriented
Programming philosophy. You can use procedural programming most of the time, but sometimes when you want to write large programs or find a more appropriate solution, you have to use object-oriented programming technology.
Class and object are two main aspects of object-oriented programming. Class to create a new type, and the instance of the Class Object. This is similar to a variable of the int type. The variable that stores integers is an instance of the int class (object ).
Comments to C/C ++/Java/C # programmers
Note that even integers are used as objects (belongs to the int class ). This is different from C ++ and Java (Before Version 1.5) that take integers purely as types. Use help (INT) to learn more about this class. C # and Java 1.5 programmers will be familiar with this concept because it is similar to the concept of encapsulation and solution encapsulation.
Objects can use common variables that belong to objects to store data. A variable of an object or class is called a field. Objects can also use functions of classes. Such a function is called a class method. These terms help us distinguish them from isolated functions and variables. Fields and methods can be collectively called class attributes.
There are two types of domain: the object that belongs to each instance/class or the class itself. They are called instance variables and class variables respectively.
Class is created using the class keyword. Class fields and methods are listed in an indention block.
Self
Class methods have only one special difference from common functions-they must have an additional first parameter name, but you do not assign a value to this parameter when calling this method, python provides this value. This special variable refers to the object itself, which is named self by convention.
Although you can give this parameter any name, it is strongly recommended that you use the self name-other names are not in favor of you. Using a standard name has many advantages-your program reader can quickly identify it. If you use self, some IDE (integrated development environment) can also help you.
Comments to C ++/Java/C # programmers
The self in python is equivalent to the self pointer in C ++ and the this reference in Java and C.
You must be wondering how Python assigns values to self and why you don't need to assign values to it. This can be clarified by an example. Assume that you have a class called myclass and an instance of this class.
Myobject. When you call this object method myobject. Method (arg1,
This will automatically convert from Python to myclass. Method (myobject, arg1, arg2)-this is the principle of self.
This also means that if you have a method that does not require a parameter, you still have to define a self parameter for this method.
The following example shows a class that is as simple as possible.
Create a class
Example 11.1 create a class
#! /Usr/bin/Python
# Filename: simplestclass. py
Class person:
Pass # An empty Block
P = person ()
Print P
Object Method
We have discussed that classes/objects can have methods like functions. The difference between these methods and functions is only an extra self variable. Now let's take an example.
Object Method
Example 11.2 how to use an object
#! /Usr/bin/Python
# Filename: method. py
Class person:
Def sayhi (Self ):
Print 'hello, how are you? '
P = person ()
P. sayhi ()
_ Init _ Method
There are many methods in the python class whose names have special significance. Now we will learn the meaning of the _ init _ method.
The _ init _ method runs immediately when an object of the class is created. This method can be used to initialize your object. Note that the start and end of the name are double underscores.
Use the _ init _ Method
For example, 11.3 use the _ init _ method.
#! /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 ()
# This short example can also be written as person ('swaroop '). sayhi ()
Class and object Methods
We have discussed the functions of classes and objects. Now let's take a look at its data section. In fact, they are only common variables bound to the namespace of classes and objects, that is, these names are valid only on the premise that these classes and objects.
There are two types of domains: class variables and object variables. They are differentiated based on whether the class or object owns the variable.
Class variables are shared by all objects (instances) of a class. Only one class variable is copied, so when an object changes the class variable, this change will be reflected on all other instances.
The object variables are owned by each object/instance of the class. Therefore, each object has its own copy of this domain, that is, they are not shared. In different instances of the same class, although the object variables have the same name, however, they are unrelated. This is easy to understand through an example.
Use variables of classes and objects
Example 11.4 use variables of classes and objects
#! /Usr/bin/Python
# Filename: objvar. py
Class person:
'''Represents a person .'''
Population = 0
Def _ init _ (self, name ):
'''Initializes the person's data .'''
Self. Name = Name
Print '(initializing % s)' % self. Name
# When this person is created, he/she
# Adds to the population
Person. Population + = 1
Def _ del _ (Self ):
''' I am dying .'''
Print '% s says bye.' % self. Name
Person. Population-= 1
If person. Population = 0:
Print 'I am the last one .'
Else:
Print 'there are still % d people left. '% person. Population
Def sayhi (Self ):
'''Greeting by the person.
Really, that's all it does .'''
Print 'Hi, my name is % S. '% self. Name
Def howmany (Self ):
'''Prints the current population .'''
If person. Population = 1:
Print 'I am the only person here .'
Else:
Print 'we have % d persons here. '% person. Population
Swaroop = person ('swaroop ')
Swaroop. sayhi ()
Swaroop. howoop ()
Kalam = person ('Abdul kalam ')
Kalam. sayhi ()
Kalam. Howmany ()
Swaroop. sayhi ()
Swaroop. howoop ()
(Source file: code/objvar. py)
Output
$ Python objvar. py
(Initializing swaroop)
Hi, my name is swaroop.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Hi, my name is swaroop.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.
How it works
This is a long example, but it helps to describe the nature of the variables of classes and objects. Here, population belongs to the person class, so it is a class variable. The name variable belongs to the object (which uses self to assign values). Therefore, it is the variable of the object.
We can see that the _ init _ method uses a name to initialize the person instance. In this method, we increase population by 1 because we have added a person. We can also find that the value of self. Name is specified based on each object, which indicates the essence of self. name as the object variable.
Remember, you can only use the self variable to refer to the variables and methods of the same object. This is called attribute reference.
In this program, we also see that docstring is equally useful for classes and methods. We can use person. _ Doc _ and person. sayhi. _ Doc _ at runtime to separate document strings of the handler class and method.
Like the _ init _ method, there is also a special method _ del __, which is called when the object disappears. The object is no longer used, and the memory occupied by the object will be returned to the system for use. In this method, we simply subtract 1 from person. Population.
When the object is no longer used, the __del _ method runs, but it is difficult to ensure when the method runs. If you want to specify how it runs, you have to use the del statement, as we used in previous examples.
Comments to C ++/Java/C # programmers
All class members (including data members) in Python are public and all methods are valid.
Only one exception: if you use a data member name with a double-underline prefix such as _ privatevar, the python name management system will effectively use it as a private variable.
In this way, there is a convention that if a variable only needs to be used in a class or object, it should be prefixed with a single underscore. Other names are public and can be used by other classes/objects. Remember that this is just a convention and is not required by Python (different from the double-underline prefix ).
Similarly, the _ del _ method is similar to the Destructor method.
Inheritance
One of the main benefits of object-oriented programming is code reuse. One of the ways to achieve this reuse is through the inheritance mechanism. Inheritance can be fully understood as the relationship between types and subtypes between classes.
Suppose you want to write a program to record the teachers and students in the school. They have common attributes, such as names, ages, and addresses. They also have proprietary attributes, such as teachers' salaries, courses and holidays, students' scores and tuition fees.
You can create two independent classes for the instructors and students to process them. However, if you want to add a new common attribute, this means that this attribute must be added to both independent classes. This will soon become impractical.
A better way is to create a common class called schoolmember and let the classes of teachers and students inherit this common class. That is, they are all subtypes of this type (class), and then we add proprietary attributes for these subtypes.
This method has many advantages. If we add/change any feature in schoolmember, it will be automatically reflected in the Child type. For example, you want to add a new one for both teachers and students.
Then you simply add it to the schoolmember class. However, the changes made in a subtype do not affect other subtypes. Another advantage is that you can
And the student object are used as schoolmember objects, which is particularly useful in some occasions, such as counting the number of school members. A child type can be replaced with a parent type in any scenario where the parent type is required.
Type, that is, the object can be considered as an instance of the parent class. This phenomenon is called polymorphism.
In addition, we will find that when reusing the code of the parent class, we do not need to repeat it in different classes. If we use an independent class, we have to do so.
In the preceding scenario, the schoolmember class is called a basic class or a superclass. The teacher and student classes are called export classes or subclasses.
Now we will learn an example program.
Use inheritance
Example 11.5 use inheritance
#! /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: % s)' % self. Name
Def tell (Self ):
'''Tell my details .'''
Print 'name: "% s" Age: "% s" '% (self. Name, self. Age ),
Class teacher (schoolmember ):
'''Represents a teacher .'''
Def _ init _ (self, name, age, salary ):
Schoolmember. _ init _ (self, name, age)
Self. Salary = salary
Print '(initialized Teacher: % s)' % self. Name
Def tell (Self ):
Schoolmember. Tell (Self)
Print 'salary: "% d" '% 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: % s)' % self. Name
Def tell (Self ):
Schoolmember. Tell (Self)
Print 'Marks: "% d" '% self. Marks
T = teacher ('Mrs. shrividya', 40,300 00)
S = student ('swaroop ', 22, 75)
Print # prints a blank line
Members = [t, s]
For member in members:
Member. Tell () # works for both teachers and students
(Source file: code/inherit. py)
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: "22" marks: "75"
How it works
To use inheritance, we use the basic class name as a tuples after the class name when defining the class. Then, we noticed that the _ init _ method of the basic class is called using the self variable.
We can initialize the basic class of the object. This is important at 01:10 -- Python does not automatically call the constructor of the basic class. You have to call it in person.
We also observe that we add the class name prefix before the method call, and then pass the self variable and other parameters to it.
Note that when we use the tell method of the schoolmember class, we only use the instance of teacher and student as the instance of schoolmember.
In addition, in this example, we call the tell method of the child type, instead of the tell method of the schoolmember class. It can be understood that python always finds the corresponding
Type method, which is used in this example. If it cannot find the corresponding method in the export class, it will start to search for it one by one in the basic class. The basic class is specified in the tuples when the class is defined.
Annotation of a term-if more than one class is listed in the inheritance tuples, it is called multi-inheritance.