Learn Python The Hard Way learning (40)-modules, classes and objects

Source: Internet
Author: User

Python is an object-oriented programming language, that is, python allows you to use class to organize your own software. Class can make your program more consistent and easier to call. In theory, this is the case.

Now we use the dictionary and module we just learned to explain object-oriented programming, classes, and objects. My point is that OOP is a very strange thing. Why do we say so? I will explain this chapter first and the next exercise.

Modules are like dictionaries.
You already know how dictionaries are created and used, and you can map one thing to another, for example:
Mystuff = {'apple': "I am apples! "}
Print mystuff ['apple']

Keep the idea of taking y from x, which is similar to the module. You still need to know about the module:
A python file containing many variables and functions
You can import this file
You can use. To access functions and variables in the module.
Imagine that I have a module file containing the apple function mystuff. py:
Def apple ():
Print "I am apples! "

I can use the following method to use the apple function:
Import mystuff
Mystuff. apple ()

You can also add a variable in mystuff:
Def apple ():
Print "I am apples! "

Tangerine = "Living reflection of a dream"

Access using the same method:
Import mystuff
Mystuff. apple ()
Print mystuff. tangerine

Let's compare the modules and dictionaries:
Mystuff ['apple']
Mystuff. apple ()
Mystuff. tangerine

This indicates that python has a common mode:
Creates a key = value mode.
Call value by key name
In the dictionary, the key is a string, and the call syntax is [key]. In the module, the key is the identifier, and the call method is. key. These two items are similar.

Class is like a module
You can think of a module as a special dictionary. It can save python code and call it by A. Number. Python also has a structure similar to implementing this purpose, called classes. A class contains many functions and data and can be accessed through.

If I want to write a class similar to mystuff, it is like this:
Class mystuff (object ):
Def _ int _ (self ):
Self. tangerine = "Hello"

Def apple (self ):
Print "apple"

It is a bit more complicated than a module, but you can think of it as a mini module. What is confusing is that the _ init _ () function and self. tangerine set the value of the tangerine variable.

Here is the reason for using classes to replace modules: You can use the same class in a program for many times. They do not affect each other, but only one module can be imported into a program.

Before understanding this, you must understand what objects are.

The object is like a mini import.
If the class image module is used, the class also has the import function of the Type module. It is instantiation. If you instantiate a class, you get an object.

The method of using a class is similar to calling a function, as shown in the following code:
Thing = mystuff ()
Thing. apple ()
Print thing. tangerine

The first step is to instantiate and then call its function. We can use the above Code to analyze how python is executed in order:
Python looks for Myclass to see if you have defined this class.
Python creates an empty object for the function defined in the class.
If there is a magic method _ init __in the class, you will use this function to initialize your empty object.
There is an extra variable self in the _ init _ method. This is the empty object created by python. You can assign values to this variable.
In this case, I assigned the lyrics to thing. tangerine and initialized the object.
Now python can assign this finished object to a variable thing.
This is why we import a class just like calling a function.

Remember, I am not giving a very accurate class working method, just to better understand the class through the module. The fact is that classes and objects and modules are not one thing. To be honest, they are like the following:
Class is like a blueprint, which is defined to create a mini module.
Instantiation means that this mini module is used for import at the same time.
The created mini-module is an object, which is assigned to a variable and then used to work.
Although it is difficult to transition from a module to a class and an object, this method is better understood.

Extract from something
There are three methods:
# Dictionary
Mystuff ['apple']

# Module
Mystuff. apple ()
Print mystuff. tangerine

# Class
Thing = mystuff ()
Thing. apple ()
Print thing. tangerine

First Class
You may still have a lot of questions. Don't worry. Put these questions into consideration for the moment. Let's take a look at the object-oriented knowledge of our school in the next exercise. Let's take a look at the class Writing Method and prepare for the next exercise.
[Python]
Class Song (object ):
 
 
Def _ init _ (self, lyrics ):
Self. lyrics = lyrics
 
 
Def sing_me_a_song (self ):
For line in self. lyrics:
Print line
 
 
Happy_bday = Song (["Happy birthday to you ",
"I don't want to get sued ",
"So I'll stop right there"])
 
 
Bulls_on_parade = Song (["they relly around the family ",
"With pockets full of shells"])
 
 
Happy_bday.sing_me_a_song ()
Bulls_on_parade.sing_me_a_song ()


Running result
Happy birthday to you
I don't want to get sued
So I'll stop right there
They relly around the family
With pockets full of shells

Extra score exercise
1. Print more lyrics and make sure you know that we passed a list to the lyrics in the class.

2. Separate the lyrics and use different variables, and then pass them to the class for use.

3. Try to do more things without worrying about destroying this class.

4. Find an object-oriented programming knowledge on the Internet. If it makes no sense to you, don't worry. Half of these things do not make sense to me.

Author: lixiang0522

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.