Common functions and descriptions of Python learning notes

Source: Internet
Author: User
Tags floor division month name time and date timedelta

Basic customization type

Copy codeThe Code is as follows:
C. _ init _ (self [, arg1,...]) constructor (with some optional parameters)
C. _ new _ (self [, arg1,...]) constructor (with some optional parameters); it is usually used to set a subclass of the unchanged data type.
C. _ del _ (self) Deconstruct
C. _ str _ (self) printable character output; built-in str () and print statements
C. _ repr _ (self) string output during runtime; built-in repr () and ''Operators
C. _ unicode _ (self) B Unicode string output; built-in unicode ()

C. _ call _ (self, * args) indicates the callable instance.
C. _ nonzero _ (self) defines the False value for the object; built-in bool () (starting from Version 2.2)
C. _ len _ (self) "length" (can be used for classes); built-in len ()

Special method description
Object (value) Comparison c
Copy codeThe Code is as follows:
C. _ cmp _ (self, obj) object comparison; built-in cmp ()
C. _ lt _ (self, obj) and smaller than/less than or equal to; corresponding <and <= Operators
C. _ gt _ (self, obj) and greater than/or equal to; corresponding to> and> = Operators
C. _ eq _ (self, obj) and equals/not equal to; corresponding = ,! = And <> Operators

Attribute
Copy codeThe Code is as follows:
C. _ getattr _ (self, attr) Get attributes; built-in getattr (); called only when the attribute is not found
C. _ setattr _ (self, attr, val) set attributes
C. _ delattr _ (self, attr) delete attributes
C. _ getattribute _ (self, attr) Get attributes; built-in getattr (); always called
C. _ get _ (self, attr) (descriptor) get attributes
C. _ set _ (self, attr, val) (descriptor) set attributes
C. _ delete _ (self, attr) (descriptor) delete attributes

Custom class/simulation type
Value Type: binary operator

Copy codeThe Code is as follows:
C. _ * add _ (self, obj) plus; + operator
C. _ * sub _ (self, obj) subtraction;-Operator
C. _ * mul _ (self, obj) multiplication; * operator
C. _ * div _ (self, obj) Division;/Operator
C. _ * truediv _ (self, obj) True division;/Operator
C. _ * floordiv _ (self, obj) Floor division; // Operator
C. _ * mod _ (self, obj) modulo/remainder; % Operator
C. _ * divmod _ (self, obj) division and modulo; built-in divmod ()
C. _ * pow _ (self, obj [, mod]) multiplication power; built-in pow (); ** Operator
C. _ * lshift _ (self, obj) Left shift; <Operator

Special method description
Custom class/simulation type
Value Type: binary operator

Copy codeThe Code is as follows:
C. _ * rshift _ (self, obj) shifts right;> Operator
C. _ * and _ (self, obj) bitwise and; & operator
C. _ * or _ (self, obj) bitwise or; | Operator
C. _ * xor _ (self, obj) bitwise AND or; ^ Operator

Value Type: unary operator

Copy codeThe Code is as follows:
C. _ neg _ (self) negative of one dollar
C. _ pos _ (self) mona1 positive
C. _ abs _ (self) absolute value; built-in abs ()
C. _ invert _ (self) reverse by bit ;~ Operator

Value Type: Numerical Conversion

Copy codeThe Code is as follows:
C. _ complex _ (self, com) to complex (plural); built-in complex ()
C. _ int _ (self) to int; built-in int ()
C. _ long _ (self) to long; built-in long ()
C. _ float _ (self) to float; built-in float ()

Value Type: basic notation (String)

Copy codeThe Code is as follows:
C. _ oct _ (self) octal representation; built-in oct ()
C. _ hex _ (self) hexadecimal representation; built-in hex ()

Numeric type: Numerical Compression

Copy codeThe Code is as follows:
C. _ coerce _ (self, num) compressed to the same numeric type; built-in coerce ()
C. _ index _ (self) g. When necessary, compress the optional numeric type into an integer (for example, used for slicing ).
Index, etc.

Sequence type

[Code]
Number of items in the C. _ len _ (self) sequence
C. _ getitem _ (self, ind) to obtain a single sequence element
C. _ setitem _ (self, ind, val) set a single sequence element
C. _ delitem _ (self, ind) delete a single sequence element

Special method description
Sequence type

Copy codeThe Code is as follows:
C. _ getslice _ (self, ind1, ind2) to obtain the sequence segment
C. _ setslice _ (self, i1, i2, val)
C. _ delslice _ (self, ind1, ind2) delete a sequence segment
C. _ contains _ (self, val) f Test Sequence member; built-in in keyword
C. _ * add _ (self, obj) concatenate; + operator
C. _ * mul _ (self, obj) repetition; * operator
C. _ iter _ (self) Create iteration class; built-in iter ()

Ing type

Copy codeThe Code is as follows:
C. _ len _ (self) number of items in ing
C. _ hash _ (self) hash function value
C. _ getitem _ (self, key) Get the value of the given key.
C. _ setitem _ (self, key, val) sets the value of the given key.
C. _ delitem _ (self, key) Delete the value of the given key
C. _ missing _ (self, key) if the given key does not exist in the dictionary, a default value is provided.

Remember several common python functions to avoid forgetting
Get the file extension function: return the file name path before the extension and extension.

Copy codeThe Code is as follows:
OS .path.splitext('xinjingbao1s.jpg ')
('Xinjingbao1s ', '.jpg ')

OS and OS. path modules
Copy codeThe Code is as follows:
OS. listdir (dirname): List directories and files under dirname
OS. getcwd (): Get the current working directory
OS. curdir: returned but the former directory ('.')
OS. chdir (dirname): change the working directory to dirname

OS. path. isdir (name): determines whether the name is a directory. If the name is not a directory, false is returned.
OS. path. isfile (name): determines whether the name is a file. If the name does not exist, false is returned.
OS. path. exists (name): determines whether a file or directory name exists.
OS. path. getsize (name): Get the file size. If the name is a directory, return 0L
OS. path. abspath (name): Obtain the absolute path.
OS. path. normpath (path): standard path string format
OS. path. split (name): split the file name and directory (in fact, if you fully use the directory, it will also separate the last directory as the file name, and it will not determine whether the file or directory exists)
OS. path. splitext (): separates file names and extensions
OS. path. join (path, name): Connection directory and file name or directory
OS. path. basename (path): returns the file name.
OS. path. dirname (path): Return file path


1. rename: OS. rename (old, new)

2. Delete: OS. remove (file)

3. List the files in the directory: OS. listdir (path)

4. Get the current working directory: OS. getcwd ()

5. Change the working directory: OS. chdir (newdir)

6. Create a multilevel Directory: OS. makedirs (r "c: \ python \ test ")

7. Create a single directory: OS. mkdir ("test ")

8. Delete multiple directories: OS. removedirs (r "c: \ python") # delete all empty directories in the last directory of the given path.

9. delete a single directory: OS. rmdir ("test ")

10. Get file attributes: OS. stat (file)

11. Modify the file Permission and timestamp: OS. chmod (file)

12. Execute the operating system command: OS. system ("dir ")

13. Start a new process: OS .exe c (), OS .exe cvp ()

14. Execute the program in the background: osspawnv ()

15. Terminate the current process: OS. exit (), OS. _ exit ()

16. Separated file name: OS. path. split (r "c: \ python \ hello. py") --> ("c: \ python", "hello. py ")

17. separation Extension: OS. path. splitext (r "c: \ python \ hello. py ") --> (" c: \ python \ hello ",". py ")

18. Obtain the path name: OS. path. dirname (r "c: \ python \ hello. py") --> "c: \ python"

19. Get the file name: OS. path. basename (r "r: \ python \ hello. py") --> "hello. py"

20. Determine whether the file exists: OS. path. exists (r "c: \ python \ hello. py") --> True

21. Determine whether the path is absolute: OS. path. isabs (r ". \ python \") --> False

22. Check whether the directory is OS. path. isdir (r "c: \ python") --> True

23. Determine whether the file is: OS. path. isfile (r "c: \ python \ hello. py") --> True

24. Determine whether the file is a linked file: OS. path. islink (r "c: \ python \ hello. py") --> False

25. Get file size: OS. path. getsize (filename)

26. *******: OS. ismount ("c: \") --> True

27. Search all files in the directory: OS. path. walk ()

[2. shutil]

1. copy a single file: shultil. copy (oldfile, newfle)

2. Copy the entire directory tree: shultil. copytree (r ". \ setup", r ". \ backup ")

3. Delete the entire directory tree: shultil. rmtree (r ". \ backup ")

[3. tempfile]

Copy codeThe Code is as follows:
1. Create a unique temporary file: tempfile. mktemp () --> filename

2. Open the temporary file: tempfile. TemporaryFile ()

[4. StringIO] # cStringIO is a fast implementation module of the StringIO module.

1. Create a memory file and write the initial data: f = StringIO. StringIO ("Hello world! ")

2. read Memory file data: print f. read () # or print f. getvalue () --> Hello world!

3. write Data to memory files: f. write ("Good day! ")

4. close the memory file: f. close ()

View Source code printing help

Copy codeThe Code is as follows:
From time import *

Def secs2str (secs ):
Return strftime ("% Y-% m-% d % H: % M: % S", localtime (secs ))

>>> Secs2str (1227628280.0)
'2017-11-25 23:51:20'

Returns the specified struct_time (current time by default) according to the specified formatted string.
Time and date formatting symbols in python:
% Y two-digit year (00-99)
% Y indicates the four-digit year (000-9999)
% M month (01-12)
One day in % d month (0-31)
% H hour in 24-hour format (0-23)
% I 12-hour (01-12)
% M minutes (00 = 59)
% S seconds (00-59)

% A local simplified week name
% A local full week name
% B local simplified month name
% B local full month name
% C local Date and Time
% J one day in the year (001-366)
% P local equivalent of A. M. or P. M.
% U number of weeks in a year (00-53) Sunday is the start of the week
% W Week (0-6), Sunday is the beginning of the week
% W number of weeks in a year (00-53) Monday is the start of the week
% X local date Representation
% X Local Time Representation
% Z Current Time Zone name
% Itself

9. strptime (...)
Strptime (string, format)-> struct_time
Converts a time string to a time string in the array format based on the specified formatting character.
For example:
The format string for 11:45:39 is: % Y-% m-% d % H: % M: % S
Sat Mar 28 22:24:24 2009 formatted string: % a % B % d % H: % M: % S % Y

10. time (...)
Time ()-> floating point number
Returns the timestamp of the current time.

Iii. Doubts
1. Renewal
In struct_time, it seems useless to parse, for example
A = (2009, 6, 28, 23, 8, 34, 5, 87, 1)
B = (2009, 6, 28, 23, 8, 34, 5, 87, 0)
A and B indicate the time stamp and the standard time respectively. The conversion between them is related to the timestamp 3600, but the output is 646585714.0 after the conversion.

4. Small applications
1. Obtain the current time using python
Time. time () Get the current Timestamp
Time. localtime () struct_time form of the current time
Time. ctime () string format of the current time

2. format strings in python
Formatted as 11:45:39
Copy codeThe Code is as follows:
Time. strftime ("% Y-% m-% d % H: % M: % S", time. localtime () is formatted as Sat Mar 28 22:24:24 2009

Time. strftime ("% a % B % d % H: % M: % S % Y", time. localtime () 3. Convert the format string to a timestamp

A = "Sat Mar 28 22:24:24 2009"
B = time. mktime (time. strptime (a, "% a % B % d % H: % M: % S % Y "))

Python time datetime module details

Time module:
--------------------------
Time () # returns the number of seconds since the Linux New Century in floating point format. In linux, 00:00:00 UTC,

January 1, 1970 is the beginning of the new ** 49.
>>> Time. time ()
1150269086.6630149
>>> Time. ctime (1150269086.6630149)
>>> 'Wed Jun 14 15:11:26 123'

Time. ctime ([sec]) # converts the number of seconds to the date format. If no parameter is included, the current time is displayed.

>>> Import time
>>> Time. ctime ()
>>> 'Wed Jun 14 15:02:50 123'
>>> Time. ctime (1138068452427683)
'Sat Dec 14 04:51:44 123'
>>> Time. ctime (OS. path. getmtime ('e: \ untitleds.bmp '))
'Fri Sep 19 16:35:37 123'

>>> Time. gmtime (OS. path. getmtime ('e: \ untitleds.bmp '))
Time. struct_time (maid = 2008, tm_mon = 9, tm_mday = 19, tm_hour = 8, tm_min = 35,

Tm_sec = 37, tm_wday = 4, tm_yday = 263, tm_isdst = 0)

Convert the modification time of a file to the date format (second to date)
>>> Time. strftime ('% Y-% m-% d % x', time. localtime (OS. path. getmtime ('e: \ untitleds.bmp ')))
'2017-09-19 16:35:37'

# Timed for 3 seconds.
>>> Time. sleep (3)

TIME module reference:
---------------------------------
# Retrieve the modification time of an object
>>> OS. path. getmtime ('e: \ untitleds.bmp ')
1221813337.7626641

Variable
The difference between the timezone universal coordination time and the local standard time, in seconds.
Difference between the altzone universal coordination time and local compaction time
Daylight indicates whether the local time reflects the daylight saving time.
Tzname (Standard Time Zone name, Time Zone name in milliseconds)
Function
Time () returns the number of seconds since the epoch.
Clock () returns the time when the CPU starts the process with a floating point number (or the time when the function is called the first time)
Sleep () delays the number of seconds represented by floating points.
Gmtime () converts the time expressed in seconds to a Universal Coordinated time sequence.
Localtime () converts seconds to Local Time Series
Asctime () converts a time series into a text description
Ctime () converts a second to a text description
Mktime () converts a local time sequence to a second
Strftime () converts a sequence to a text description in a specified format
Strptime () parses time series from text descriptions in a specified format
Tzset () changes the local time zone value

DateTime Module
----------------------------
Datetime converts a date to a second.
-------------------------------------
>>> Import datetime, time
>>> Time. mktime (datetime. datetime (2009, 1, 1). timetuple ())
1230739200.0

>>> Cc = [, 11,] # Attributes: year, month, day, hour, minute,

Second
>>> Time. mktime (datetime. datetime (cc [0], cc [1], cc [2], cc [3], cc [4], cc [5]). timetuple ())
973226613.0

Convert seconds to date format
>>> Cc = time. localtime (OS. path. getmtime ('e: \ untitleds.bmp '))
>>> Print cc [0: 3]
(2008, 9, 19)

DateTime example
-----------------
Computing the number of days for calculating the difference between two dates
>>> Import datetime
>>> D1 = datetime. datetime (2005, 2, 16)
>>> D2 = datetime. datetime (2004, 12, 31)
>>> (D1-d2). days
47

Demo of computing run time, displayed in seconds
Import datetime
Starttime = datetime. datetime. now ()
# Long running
Endtime = datetime. datetime. now ()
Print (endtime-starttime). seconds

This example calculates the time from the current time to the next 10 hours.
>>> D1 = datetime. datetime. now ()
>>> D3 = d1 + datetime. timedelta (hours = 10)
>>> D3.ctime ()

Common classes include datetime and timedelta. They can be added or subtracted from each other. Each class has some methods and attributes to view specific values.

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.