Object-oriented 2 of Python

Source: Internet
Author: User
Tags class definition sleep function

Hide Data

You may have realized that there are two ways to view or modify data (properties) in an object. can be accessed directly, like this:

Mydog.cooked_level = 5

Alternatively, you can use methods that modify the properties, such as:

Mydog.cook (5)

If a hot dog is born at the beginning (cooked_level = 0), the two practices work the same way. They all set the Cooked_level to 5. So why bother to build a way to do the job? Why not modify it directly?

I can think of at least two reasons.

? If the property is accessed directly, the grilled hotdog needs at least two parts: changing the cooked_level and changing the cooked_string. And with a method, you can do just one method call, and it will do everything we need.

? If you access the property directly, you will get the result:

Cooked_level = Cooked_level-2

This will make the hot dog more alive than before. But the hot dogs won't bake more! So it's pointless. By using the method, you can ensure that the cooked_level will only increase without decreasing.

Term Box

In terms of programming terminology, restricting access to object data makes it possible to obtain and modify this data only by using methods, known as data hiding. Python does not provide any way to keep data hidden, but if you want, you can write code appropriately to follow this rule.

So far, we've seen objects containing properties and methods. It also learned how to create objects and how to initialize them with a special method called __init__ (). We also saw another special method, __str__ (), that can be used to better print our objects. Polymorphism and Inheritance

Next, let's look at the two most important aspects of the object: Polymorphism (polymorphism) and inheritance (inheritance). These two words are very long and abstruse, but it is because of these two aspects that makes the object so useful. I will explain clearly what they mean in the next few sections.

polymorphic -- the same method, different behavior

Very simple, polymorphic means that for different classes, there can be two (or more) methods with the same name. Depending on which class each of these methods is applied to, they can behave differently.

For example, suppose you want to create a program to do geometric problems, you need to calculate the area of different shapes, such as triangles and squares. You can create two classes, as follows:

Both the triangle class and the square class have a method called Getarea (). So, if there are instances of these two classes, they are as follows:

>>> Mytriangle = Triangle (4, 5)

>>> MySQUARE = Square (7)

You can use Getarea () to calculate their area separately:

>>> Mytriangle.getarea ()

10.0

>>> Mysquare.getarea ()

49

All two shapes use the method name Getarea (), but this method works differently in each shape. This is a polymorphic example.

Inheritance -- learn from your parents

In the real (non-programmed) world, people can inherit something from their parents or other relatives. You can inherit traits such as red hair, or you can inherit things like money and possessions.

In object-oriented programming, classes can inherit properties and methods from other classes. This will have the entire "family" of classes, each of which shares the same properties and methods in the "Family". This way, you don't have to start from scratch each time you add a new member to the family.

Classes that inherit properties or methods from other classes are called derived classes (derived class) or subclasses (subclass). An example can be given to explain the concept.

Suppose we want to build a game where players can pick up different things, like food, money or clothes. You can build a class named Gameobject. The Gameobject class has properties such as name, such as coin, apple, or hat, and pickup () (which adds coins to the player's collection of items). All game objects have these common methods and properties.

Then, you can create a subclass for the coin. The coin class derives from Gameobject. It inherits the properties and methods of Gameobject, so the coin class automatically has a Name property and a pickup () method. The coin class also needs a Value property (how much the coin is worth) and a spend () method (which can be used to buy things).

Here's a look at the code for these classes:

Rainy Day

In the example above, we did not include any actual code in the method, only some comments to explain what these methods do. This is a proactive approach, which is to plan ahead or consider the content to be added in the future. The exact code depends on how the game works. Programmers often use this approach to organize their ideas when writing more complex code. An "empty" function or method is called a code stub.

If you want to run the previous example, you get an error message because the function definition cannot be empty.

Yes, Carter, but the annotations don't work because they're just for you to read, not to be executed by the computer.

If you want to build a code pile, you can use the Python pass keyword as a placeholder. The code should actually look like this:

I'm not going to give you a more detailed example of using objects, polymorphism, and inheritance in this chapter. You'll also see a lot of examples of objects and how to use them when you learn what's behind the book. By using objects in actual programs (such as games), you will have a deeper understanding.

Give it a try.

1. Create a class definition for bankaccount. It should have some attributes, including the account name (a string), the account number (a string or integer), and the balance (a floating-point number), plus some ways to show the balance, save money, and withdraw cash.

2. Establish a class that can earn interest, called Interestaccount. This should be a subclass of BankAccount (so the properties and methods of BankAccount are inherited). Interestaccount should also have a property that corresponds to the interest rate, and there is another way to increase interest. For the sake of simplicity, assume that the Addinterest () method is called once a year to calculate interest and update the balance. Module

This is the final chapter of the discussion collection method (this is the last chapter, that talks, about ways of collecting things together.). We've learned about lists, functions, and objects, and in this chapter we'll learn about modules. In the next chapter, we'll start drawing some graphics using a module named Pygame. 1 what is a module

A module is a part of something. If a thing can be divided into several parts, or you can easily break it down into different parts, we say that this thing is modular. Lego bricks are probably the best examples of modularity. You can take a bunch of different bricks and build different things with them.

In Python, a module is a similar part that is contained in a larger program. Each module or part is a separate file on the hard disk. A large program can be decomposed into multiple modules or files. Or you can, in turn, start with a small module and gradually add other parts to build a large program. 2 Why use a module

Why bother to break up the program into smaller parts? Be aware that we need all of these parts to make the program work properly. Why not just put everything in one big file?

There are several reasons.

      • This makes the file smaller and makes it easier to find the code.
      • Once the module is created, the module can be used in many programs. The next time you need the same functionality, you don't have to start from scratch.
      • Not all modules are intended to be used. Modularity means that you can use different combinations of parts to accomplish different tasks, like using the same set of Lego bricks to build different things.
3 Brick Bucket

In the 13th chapter of the function, we said that the function is like a building block, then the module can be considered a bucket of bricks. Depending on your needs, you can take a lot or few bricks from a bucket, or you can have a lot of different bricks. There may be a bucket of square bricks, a bucket of rectangular bricks, and a barrel of grotesque bricks. Programmers often use modules in this way, which means they collect similar functions in a single module. Or they might be able to collect all the functions needed for a project in a single module, just as you would put all the bricks needed in a castle in one bucket. 4 How to create a module

Below to create the module. The module is a python file, similar to the one given in listing 15-1 of the code. In an idle editor window, type the code in Listing 1 and save it as my_module.py.

It's so easy! This creates a module! There is only one function in the module, the C_to_f () function, which converts the temperature from Celsius to Fahrenheit.

Next we use my_module.py in another program. 5 How to use modules

To use a function in a module, you first have to tell Python which modules we want to use. The Python keyword that contains other modules in the program is import. This can be used:

Import My_module

Here is a program to use the module we just wrote, here we want to use the C_to_f () function to complete the temperature conversion.

You have already learned how to use a function and pass parameters to it. The only difference here is that the function is not in the same file as the main program, but in a separate file, so import must be used. The program in code listing 15-2 uses the module my_module.py we just wrote.

Create a new Idle editor window and type this program. Save As modular.py, then run the program and see what happens. You need to save it to the same folder (or directory) where my_module.py is located.

Can you work properly? You should see a result similar to the following:

Enter a temperature in celsius:34

Traceback (most recent):

File "C:/local_documents/warren/pythonbook/sample programs/modular.py",

Line 3, in-toplevel-

fahrenheit= C_to_f (Celsius)

Nameerror:name ' C_to_f ' is not defined

The program does not work properly! What's going on? The error message indicates that the function c_to_f () is undefined. However, we know that this function has already been defined in My_module, and we have actually imported this module.

This problem occurs because specifying functions defined in other modules in Python must be more specific. One way to solve this problem is to put this line of code

Fahrenheit = C_to_f (Celsius)

Switch

Fahrenheit = My_module.c_to_f (Celsius)

Now we specifically point out to Python that the C_to_f () function is in the My_module module. Make this change and try running the program to see if it works. 6 name Space

What Carter refers to is related to the concept of namespaces (namespace). The topic is a little complicated, but it really needs to be known, so let's discuss the concept now.

What is a namespace

Suppose in your school, you in Morton Teacher's class, the class has a student named Shawn. Now the class that Wheeler teacher teaches also has a student named Shawn. If you say "Shawn has a new schoolbag" In your class, everyone in your class will know (or at least they will) that you mean the Shawn of your class. If you want to say that the other class of Shawn will say "Wheeler teacher class Shawn" or "another Shawn", or other similar statements.

There is only one Shawn in your class, so when you say Shawn, your classmates will know who you are talking about. In other words, in this space of your class, there is only one name Shawn. Your class is your namespace, there is only one Shawn in this namespace, so there is no confusion.

Now, if the headmaster had to call Shawn to the office through the school's broadcast system, she would not say "please Shawn to the office." If she did, two Shawn would appear in his office. For the headmaster using the broadcast system, the namespace is the whole school. This means that every person in the school will hear the name, not just a class of classmates. So she had to be more specific about which Shawn she was referring to. She had to say, "Please Morton the Shawn in the teacher's class to the office." ”

The headmaster can also use another method to find Shawn, is to go to your class door said: "Shawn, please follow me." "There was only one Shawn heard, so the headmaster could find the Shawn he was really looking for." In this case, the namespace is just a classroom, not the whole school.

In general, programmers refer to smaller namespaces (such as your classroom) as local namespaces, while larger namespaces, such as the entire school, are called global namespaces.

Import Namespaces

Let's assume that your school (John Young school) doesn't have a man named Fred. If the headmaster wanted to find Fred through the radio system, she would not have found this person. Now suppose another school on the same street as your school (Stephen Leacock School) is in the course of some school maintenance, and the school has temporarily moved a class to your school's activity room. In this class, there happens to be a student named Fred. But the activity room is not connected to the radio system. If the headmaster is looking for Fred, he won't find it. But if she connects this new activity room to the broadcast system and then to Fred, she will find Fred from Stephen Leacock School.

Connect to another school's active house, which in Python is like importing a module.

By importing the module, you can access all the names in the module, including all variables, functions, and objects.

The import module has the same meaning as importing a namespace. When the module is imported, the namespace is imported.

There are two methods of importing namespaces (modules). You can do this:

Import Stephenleacock

If you do this, Stephenleacock is still a separate namespace. You can access this namespace, but you must explicitly specify which namespace you want before you use it. So the headmaster has to do this:

Call_to_office (stephenleacock.fred)

If the headmaster wanted to find Fred, she would have to give the namespace (Stephen Leacock) In addition to the name (Fred). This is done in the previous temperature conversion program.

In order for this program to work properly, we wrote a line of code:

Fahrenheit = My_module.c_to_f (Celsius)

This specifies the namespace (my_module) and the function name (c_to_f).

Another way to import namespaces is to:

From Stephenleacock import Fred

If the headmaster does this, the Stephenleacock name Fred will be included in her namespace and can now find Fred:

Call_to_office (Fred)

Because Fred is now in the headmaster's namespace, she doesn't have to go to the Stephenleacock namespace to find Fred.

In this example, the headmaster simply imports the name Fred from Stephenleacock into her local namespace. If she wants to import everyone, you can do this:

From Stephenleacock Import *

Here, the asterisk (*) indicates all. But she must be careful that if Stephen Leacock School had a student of the same name as John Young's school, there would be confusion.

So far, you may not be quite sure about the concept of namespaces. Do not worry! By completing the examples in the following chapters, you will become more and more aware. I will clearly explain what to do when I need to import the module later. 7 standard modules

We already know how to create and use modules, do we always have to write our own modules? That's not true! This is one of the beauty of Python.

Python provides a number of standard modules that can be used to do a lot of work, such as finding files, telling time (or timing), generating random numbers, and many other features. Sometimes people say that Python is "equipped with batteries" and that it refers to all of Python's standard modules. This is known as the Python standard library.

Why should the content be placed in a separate module? Well, it doesn't have to be like this, but people who design python think it's more efficient. Otherwise, each Python program must contain all the functions that might be used. By creating a separate module, you just need to include those functions that you really want.

Of course, some content (such as print, for, and If-else) is a basic Python command, so these basic commands do not require a separate module, which is in the main part of Python.

If Python does not provide the right modules to do what you want to do (such as creating a graphics game), you can download additional plugin modules, which are usually free! We have included some of these plug-in modules in this book, and if you use the installer on this book website, you will install the modules. Alternatively, you can also install it individually.

Here are a few standard modules.

Time

With the time module, you can get information about your computer's clock, such as the dates and times. You can also use it to increase latency for your programs. (Sometimes the computer moves too fast, you have to slow it down.) )

The sleep () function in the time module can be used to add a delay, which means that the program can wait for a while and do nothing. It's like getting your program to sleep, and for that reason, this function is called sleep (). You can tell it how long you want it to sleep (how many seconds).

The program in Code listing 15-3 shows how the Sleep () function works. Type this program, save and run, and see what happens.

# Listing 15.3 Putting your program to sleep

# code Listing 15-3 let the program sleep

Import time

Print "How",

Time.sleep (2)

Print "is",

Time.sleep (2)

Print "You",

Time.sleep (2)

Print "Today?"

Note that when you call the sleep () function, you must precede it with time: This is because, although we have imported time with import, it does not make it part of the main program namespace. So every time you want to use the sleep () function, you must call Time.sleep ().

If you try to do this:

Import time

Sleep (5)

This is not possible, because sleep is not in our namespace. We will get an error message like this:

Nameerror:name ' sleep ' is not defined

However, if you import this way:

From time import sleep

Will tell Python, "Look for a variable called sleep in the time module (or a function or object) and include it in my namespace." "You can now use the sleep function directly without adding time to the front."

From time import sleep

print ' Hello, talk to your again in 5 seconds ... '

Sleep (5)

print ' Hi again '

If you want to get the convenience of importing a name into a local namespace (so that you don't have to specify the module name every time), but you don't know which names are required in the module, you can use an asterisk (*) to import all the names into our namespace:

From time Import *

* denotes "all" so that all available names are imported from the module. The use of this command must be particularly careful. If a name is created in our program and it is the same as a name in the time module, a conflict occurs. Importing all names with * is not a best practice, it's best to import only the parts you really need.

Remember the countdown program in the 8th chapter of code listing 8-6? Now you should know the role of Time.sleep (1) in that program.

Random number

The random module is used to generate stochastic numbers. This is useful in games and simulations.

Here's an attempt to use the random module in interactive mode:

>>> Import Random

>>> print random.randint (0, 100)

4

>>> print random.randint (0, 100)

72

Each time you use Random.randint (), you get a new random integer. Since the arguments we pass for it are 0 and 100, the resulting integers will be between 0 and 100. We use Random.randint () to create a secret number in the 1th chapter of the guessing program.

If you want a random decimal, you can use Random.random (). Do not put any arguments in parentheses, because Random.random () always provides a number between 0 and 1:

>>> Print Random.random ()

0.270985467261

>>> Print Random.random ()

0.569236541309

If you want to get a random number in the other range, say, between 0 and 10, you just need to multiply the result by 10:

>>> Print Random.random () * 10

3.61204895736

>>> Print Random.random () * 10

8.10985427783

Give it a try.

1. Write a module that contains the "Print names in uppercase" function in the 13th chapter "Try it Out". Then write a program to import the module and call this function.

2. Modify the code in Listing 15-2 to include C_to_f () in the main program's namespace. In other words, modify this code,

Thereby can be written: Fahrenheit = C_to_f (Celsius)

Instead of: Fahrenheit = my_module.c_to_f (Celsius)

3. Write a small program that generates a list of 5 random integers from 1 to 20 and print them out.

4. Write a small program that requires it to work 30 seconds and print a random decimal every 3 seconds

Object-oriented 2 of Python

Related Article

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.