"29" python shallow into six common modules

Source: Internet
Author: User
Tags readline serialization shallow copy shuffle stdin

1. Using the Copy module
The Copy module contains a function to make a copy of the object. Sometimes you may need multiple identical objects when writing a program. Copies can be made using the Copy module.
For example:
We create an ad class that has a Initfunction, parameter is name (name), School_record (learning score), color (colour)

class Ad:     def __init__(self,name,school_record,color):            self.name=name            self.school_record=school_record            self.color=color

Below we can create a new object for the ad class.
Harry=ad ("Alex", "a", "red")
Let's say we want to copy a few more to use the Copy module.

>>>import copy>>>Harry=Ad("alex",80,"red")>>>Harriet=copy.copy(Harry)>>>print(Harry.name)>>>print(Harriet.name)alexalex

In this example we create the object and mark it as Harry, and then we create a copy of the object and mark it as Harriet. Although they are all the same person, they are two completely different objects. In this case it's only a few lines of code, but when the object is more complex, the copy is more useful.

>>>Harry=Ad("alex",80,"red")>>>Carriet=Ad("Ying",99,"while")>>>Jack=Ad("Li",30,"black")>>>my_animals=[Harry,Carriet,Jack]>>>more_animals=copy.copy(my_animals)>>>print(more_animals[0].name)>>>print(more_animals[1].name)

In the first three lines, we created three objects Harry,carriet and Jack. In line fourth we add the object to the My_animals list. We copied this list with copy. Final print Results

alexYing

What happens if we change the results of a student?

>>>my_animals[0].name=10>>>print(my_animals[0].name)>>>print(more_animals[0].name)1010

Too strange, we change is not my_animals in the result, why the value of two lists have changed?
The result has changed because copy actually makes only a shallow copy, which means it doesn't copy objects from the objects we want to copy. Here, it copies the list object, but does not copy each of the objects. So what we get is a new list, but the objects are not new, and the same three objects are in the list more_animals.
Also with these variables, if we add a new ad to the first list (my_animals), it will not appear in the copy (More_animals). The following can be verified

>>>salay=[‘Tom‘,55,‘pick‘]>>>my_animals.append(salay)>>>print(len(my_animals))>>>print(len(more_animals))43

The result is as you can see!
Another function in the Copy module, Deepcopy, creates a copy of all objects in the copied object. When we use Deepcopy to replicate my_animals, we get a new list of copies of all objects. As a result, changes to the Ad object in the original list do not affect the new list. Look at the following example:

>>>more_animals=copy.deepcopy(my_animals)>>>my_animals[0].name="ALEX">>>print(my_animals[0].name)>>>print(more_animals[0].name)ALEXalex

Summary:the difference between two function shallow copy copy and deep copy deepcopy in copy module.
When you copy a list. A shallow copy does not copy the objects in the list, so a shallow copy does not add objects when the object is added to the list. If the copied list is modified, the shallow copy will follow the change. While a deep copy copies the objects in the list to a separate list, the deep copy also adds objects when the object is added to the copied list, and the deep copy does not change if the copied list is modified.

2. Using the keyword module
The keyword module records some of the python's own keywords, which are not allowed to be used for variable names. You can use the following methods to see which keywords are included.

>>>import keyword>>>print(keyword.kwlist)[‘False‘, ‘None‘, ‘True‘, ‘and‘, ‘as‘, ‘assert‘, ‘break‘, ‘class‘, ‘continue‘, ‘def‘, ‘del‘, ‘elif‘, ‘else‘, ‘except‘, ‘finally‘, ‘for‘, ‘from‘, ‘global‘, ‘if‘, ‘import‘, ‘in‘, ‘is‘, ‘lambda‘, ‘nonlocal‘, ‘not‘, ‘or‘, ‘pass‘, ‘raise‘, ‘return‘, ‘try‘, ‘while‘, ‘with‘, ‘yield‘]

3. Using the Random module
Random numbers can be obtained through the random module. Some of the most useful functions in the random module are Randint,choice and shuffle.
The 3.1 randint function is used to randomly pick a number

import randomnum=random.randint(1,10)print(num)

Here you can write a guess number game.

import randominto=int(random.randint(1,100))while True:    num=int(input("Please input number: "))    if num==into:        print("恭喜你")        break    elif num > into:        print("big")    else:        print("small")

Operation Result:

Please input number: 50smallPlease input number: 70bigPlease input number: 60smallPlease input number: 69恭喜你

The 3.2 choice function is used to randomly pick a

>>>import random>>>lists=[‘red‘,‘pick‘,‘while‘,‘black‘,‘yellow‘]>>>t=random.choice(lists)>>>print(t)black

3.3 Shuffle function to "shuffle" the list, for games like poker.

>>>import random>>>lists_shuffle=[‘red‘,‘pick‘,‘while‘,‘black‘,‘yellow‘]>>>random.shuffle(lists_shuffle)>>>print(lists_shuffle)[‘red‘, ‘yellow‘, ‘while‘, ‘black‘, ‘pick‘]

4. Using the SYS module
There are some system functions in the SYS module that are used to control the Python shell program itself.
Let's look at how to use the Exit function, the stdin and StdOut objects, and the version variable.

4.1 Exit the shell program with the Exit function

import syssys.exit()

4.2 Reading from StdIn object
The StdIn object (standard input) in the SYS module prompts the user to enter information, read into the shell program, and use it in the program. This object has a ReadLine function that reads a line of text entered from the keyboard until the user presses a carriage return.

>>>import sys>>>v=sys.stdin.readline()this is Python sys.>>>print(v)this is Python sys.

Legacy issues: ReadLine and input function differences?

4.3 Write from StdOut object
Unlike the StdIn object, the StdOut object (standard output standards export) can be used to write messages to the shell program instead of reading from it. In some ways it is the same as print, but stout is a file object.

>>>import sys>>>sys.stdout.write("this is sys")this is sys

4.4 Let's take a look at the current Python version

>>>import sys>>>print(sys.version)3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]

5. Using the time module
The time module in Python contains functions that represent times, but may not be the same as you expect.

>>>import time>>>print(time.time())1521968583.4384

The number returned for the call to time () is actually the number of seconds since the January 1, 1970 00:00:00am. Alone it seems that this rare form of representation cannot be used directly, but it has its purpose. You can use it to record how long a program executes.

import timedef lost_of(max):    start_time=time.time()    for i in range(max):        print(i)    stop_time=time.time()    print("花费时间:%s" %(stop_time-start_time))lost_of(999)

5.1 Convert dates with asctime
The Asctime function takes a tuple of dates as a parameter and converts it into a more readable form. Without any parameter calls, Asctime returns the current date and time in a readable form.

>>>import time>>>print(time.asctime())Sun Mar 25 17:10:46 2018

5.2 Use LocalTime to get the date and time

>>>import time>>>print(time.localtime())time.struct_time(tm_year=2018, tm_mon=3, tm_mday=25, tm_hour=17, tm_min=11, tm_sec=36, tm_wday=6, tm_yday=84, tm_isdst=0)

Tm_year: Year
Tm_mon: Month
Tm_mday: Date
Tm_hour: Hours
Tm_min: Minutes
Tm_sec: Sec
Tm_wday: Sunday (0 equals Monday)
Tm_yday: Days from January 1 to present
TM_ISDST: Daylight Saving time (0 not daylight saving time)

5.3 Rest for a while with sleep.

import timefor x in range(1,20):    print(x)    time.sleep(1)  ###这里sleep(1),表示休息1s

6. Using the Pickle module
Pickle module can be used to save information, originally intended as "pickles." The pickle module is used to convert Python objects into files that can be easily written and read from a file.
If you are writing a game and want to save the player's progress information, Hu, may use pickle.
For example, add a save function to the following game information.
We can save this dictionary to a file, as long as it is written to open the file, and then call the pickle inside the dump function, like this:

import picklegame_dict={    "name":"Dy",    "ID":1203,    "player":"Tank",    "money":9999}t=open("save_game","wb")  ###以二进制写入方式打开文件pickle.dump(game_dict,t) ###用dump,将game_dict信息写入文件saver_game中。这一过程叫序列化t.close() ##关闭文件

When you open the Game_dict file, you'll find it's not like a text file, but a messy mix. This type of file can be deserialized to re-read the data.

The Python object that was Pickle is also called serialization, as for why the name of the serialization, the foreigner from the I do not know, anyway, everyone is so called. However, since there is a serialization process, of course, there is deserialization, otherwise the saved file and how to read it. Deserialization is the use of the load function. The method is simple, so long as the saved file is opened in a readable manner, it can be deserialized with load. Here's how:

local_file=open("save_game","rb")t_load=pickle.load(local_file) ###将打开文件,进行反序列化,变成可读文件local_file.close()print(t_load)

"29" python shallow into six common modules

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.