Python learning path-Object-Oriented Programming

Source: Internet
Author: User

Recently, I learned python by myself and suddenly wanted to write something. I also wanted to deepen my memory and record my bit/s. Now, I want to go to the topic:
Introduction
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 you want to write large
When looking for a more appropriate solution, you need 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
There is an int type variable, which stores the integer variable as an instance (object) of the int class ).
Note that even integers are used as objects (belongs to the int class ). This and C ++, Java (Before Version 1.5) Take integers purely as the type is
Different. 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 Encapsulation
And the concept of 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. Object can also make
Use a class function to provide functions. Such a function is called a class method. These terms help us with isolated functions and changes
The quantity is separated. 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.
Class methods have only one special difference from common functions -- they must have an additional first parameter name,
You do not assign a value to this parameter during this method. Python will provide this value. This special variable refers to the object itself, which is
The name is self.
Although you can give this parameter any name, it is strongly recommended that you use the self name.
. Using a standard name has many advantages-your program reader can quickly identify it. If you use self, there are still some IDE
(Integrated development environment) can also help you.
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 named MyClass and an instance named MyObject of this class. 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
[Python] view plaincopy
#! /Usr/bin/python
# Filename: simplestclass. py
Class Person:
Pass # An empty block
P = Person ()
Print p

Output
[Html] view plaincopy
Horst @ horst-K42Jc :~ /Desktop/horstdemo/python $ python simplestclass. py
<__ Main _. Person instance at 0xb77475cc>

We use the class statement followed by the class name to create a new class. This is followed by an indented statement block to form a class body. In this example
Child, we use a blank block, which is represented by the pass statement.
Next, we use the class name followed by a pair of parentheses to create an object/instance. (We will learn more in the following chapters, for example:
How to create an instance ). For verification, we simply printed the type of this variable. It tells us that the _ main _ Module
The block contains an instance of the Person class.
Note that the computer memory address of the stored object is printed. This address will be another value on your computer, because
For Python, objects can be stored in any space.
Object Method
[Python] view plaincopy
#! /Usr/bin/python
# Filename: method. py
Class Person:
Def sayHi (self ):
Print 'hello, how are you? '
P = Person ()
P. sayHi ()
Output
[Python] view plaincopy
Horst @ horst-K42Jc :~ /Desktop/horstdemo/python $ python method. py
Hello, how are you?

_ 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 make some initial hopes for your objects.
Start-up. Note that the start and end of the name are double underscores.
[Python] view plaincopy
#! /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 ('horst ')
P. sayHi ()
Output
[Html] view plaincopy
Horst @ horst-K42Jc :~ /Desktop/horstdemo/python $ python class_init.py
Hello, my name is Horst
Here, we define the _ init _ method as a parameter name (and a common Parameter self ). In this _ init _, we only
Is to create a new domain, also known as name. Note that they are two different variables, even though they have the same name. Point number enables us
Differentiate them.
The most important thing is that we didn't specifically call the _ init _ method, but included the parameters in the circle when creating a new instance of the class.
Followed by the class name, and passed to the _ init _ method. This is an important part of this method.
Now, we can use the self. name field in our method. This is verified in the sayHi method.

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 only work with classes and
Ordinary variables bound to the object namespace, that is, these names are valid only when these classes and objects are used.
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 to a class
When the volume is changed, 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 the domain, that is, they are not shared.
In different instances of the same class, although the object variables have the same name, they are irrelevant. By using an example
Easy to understand.
[Python]
#! /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
Horst = Person ('horst ')
Horst. sayHi ()
Host. howMany ()
Kalam = Person ('Abdul kalam ')
Kalam. sayHi ()
Kalam. howMany ()
Horst. sayHi ()
Horst. howMany ()
Output:
[Html]
Horst @ horst-K42Jc :~ /Desktop/horstdemo/python $ python objvar. py
(Initializing Horst)
Hi, my name is Horst.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Hi, my name is Horst.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Horst says bye.

This example helps to illustrate the nature of variables of classes and objects. Here, population belongs to the Person class,
Therefore, 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,
This is because we have added a person. We can also find that the value of self. name is specified based on each object, which indicates that it is changed as an object.
The essence of traffic.
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 _ at runtime __
And Person. sayHi. _ doc _ respectively refer to the document strings of the category and method.
Like the _ init _ method, there is also a special method _ del __, which is called when the object disappears. The object disappears.
It is no longer used, and the memory occupied by it will be returned to the system for its use. In this method, we simply put Person. population
Minus 1.
When the object is no longer used, the __del _ method runs, but it is difficult to ensure when the method runs. If you want
If you specify its operation, you have to use the del statement, as we used in the previous example.
Haha, let's write it here today. I hope it will help you write inheritance next time.

 


 

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.