Common functions and descriptions of Python learning notes

Source: Internet
Author: User
Tags month name timedelta
Basic Custom Type

Copy the Code code as follows:


C.__init__ (self[, arg1, ...]) constructor (with some optional parameters)
C.__new__ (self[, arg1, ...]) the constructor (with some optional parameters), usually used in subclasses that set the invariant data type.
C.__del__ (self) destructor
c.__str__ (self) printable character output, built-in STR (), and print statements
C.__repr__ (self) run-time string output; built-in repr () and ' operator
C.__unicode__ (self) b Unicode string output; built-in Unicode ()

C.__call__ (self, *args) represents a callable instance
C.__nonzero__ (self) defines the value false for object; built-in BOOL () (starting with version 2.2)
C.__len__ (self) "Length" (available for classes); built-in Len ()

Special Method Description
Object (value) comparison C
Copy the Code code as follows:


C.__cmp__ (self, obj) object comparison; built-in CMP ()
C.__lt__ (self, obj) and less than/less than or equal to; <及<=操作符
C.__gt__ (self, obj) and greater than/greater than or equal to; corresponding > and >= operators
C.__eq__ (self, obj) and equals/not equals; corresponding ==,!= and <> operators


Property
Copy CodeThe code is as follows:


C.__getattr__ (self, attr) Gets the property, built-in GetAttr (); called only if the property is not found
C.__setattr__ (self, attr, Val) setting properties
C.__delattr__ (self, attr) Delete property
C.__getattribute__ (self, attr) gets the attribute; built-in getattr (); always called
C.__get__ (self, attr) (descriptor) Get property
C.__set__ (self, attr, Val) (descriptor) Set property
C.__delete__ (self, attr) (descriptor) Delete property


Custom class/simulation type
Numeric type: binary operator

Copy the Code code as follows:


C.__*add__ (self, obj) plus; + operator
C.__*sub__ (self, obj) minus;-operator
C.__*mul__ (self, obj) by; * operator
C.__*div__ (self, obj) except;/operator
C.__*truediv__ (self, obj) True except;/operator
C.__*floordiv__ (self, obj) floor except;//Operator
C.__*mod__ (self, obj) modulo/take redundancy;% operator
C.__*divmod__ (self, obj) except and modulo; built-in Divmod ()
C.__*pow__ (self, obj[, mod]), built-in POW (); * * operator
C.__*lshift__ (self, obj) left shift;< <操作符

Special Method Description
Custom class/simulation type
Numeric type: binary operator

Copy the Code code as follows:


C.__*rshift__ (self, obj) Move right;>> operator
C.__*and__ (self, obj) bitwise AND;& operators
C.__*or__ (self, obj) bitwise OR; | operator
C.__*xor__ (self, obj) bitwise and OR; ^ operator

Numeric type: unary operator

Copy the Code code as follows:


C.__neg__ (self) One dollar negative
C.__pos__ (self) is a dollar
C.__abs__ (self) absolute value; built-in ABS ()
C.__INVERT__ (self) bitwise negation; ~ operator

Numeric type: Numeric conversion

Copy the Code code 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 ()

Numeric type: basic notation (String)

Copy the Code code as follows:


C.__oct__ (self) octal representation; built-in Oct ()
c.__hex__ (self) hexadecimal representation; built-in Hex ()

Numeric type: Numeric compression

Copy the Code code as follows:


C.__COERCE__ (self, num) is compressed into the same numeric type; built-in coerce ()
C.__index__ (self) g when necessary, the compression optional numeric type is integer (for example: for slicing
Index, etc.

Sequence type

[Code]
The number of items in the c.__len__ (self) sequence
C.__GETITEM__ (self, Ind) gets a single sequence element
C.__setitem__ (self, Ind,val) sets a single sequence element
C.__DELITEM__ (self, IND) delete a single sequence element

Special Method Description
Sequence type

Copy the Code code as follows:


C.__getslice__ (self, ind1,ind2) get sequence Fragment
C.__setslice__ (self, i1, i2,val) set sequence fragment
C.__delslice__ (self, ind1,ind2) Delete sequence fragment
C.__contains__ (self, val) f test sequence member; built in keyword
c.__*add__ (self,obj) concatenation; + operator
c.__*mul__ (self,obj) repetition; * operator
C.__iter__ (self) creates an iterative class; built-in ITER ()

Mapping type

Copy the Code code as follows:


The number of items in the c.__len__ (self) mapping
C.__hash__ (self) hash (hash) function value
c.__getitem__ (Self,key) Gets the value of the given key (key)
C.__SETITEM__ (self,key,val) Sets the value of the given key (key)
c.__delitem__ (Self,key) Delete the value of the given key (key)
C.__MISSING__ (Self,key) Given a key if it does not exist in the dictionary, provide a default value

Remember a few common python functions, lest you forget
Get the file extension function: Returns the path to the file name before the extension and the expanded name.

Copy the Code code as follows:


Os.path.splitext (' xinjingbao1s.jpg ')
(' Xinjingbao1s ', '. jpg ')

OS and Os.path modules
Copy the Code code as follows:


Os.listdir (dirname): List directories and files under DirName
OS.GETCWD (): Get current working directory
Os.curdir: Return but previous directory ('. ')
Os.chdir (dirname): Changing the working directory to DirName

Os.path.isdir (name): Determine if Name is a directory, name is not a directory and return false
Os.path.isfile (name): Determine if name is not a file, does not exist name also returns false
Os.path.exists (name): Determine if there is a file or directory name
Os.path.getsize (name): Get file size, if name is directory return 0L
Os.path.abspath (name): Get absolute path
Os.path.normpath (PATH): Canonical path string form
Os.path.split (name): Split file name and directory (in fact, if you use the directory completely, 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 (): Detach file name and extension
Os.path.join (path,name): Connection directory with file name or directory
Os.path.basename (PATH): Return file name
Os.path.dirname (PATH): Return file path


1. Renaming: Os.rename (old, new)

2. Delete: Os.remove (file)

3. List files in directory: Os.listdir (PATH)

4. Get current working directory: OS.GETCWD ()

5. Change of 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") #删除所给路径最后一个目录下所有空目录.

9. Delete a single directory: Os.rmdir ("Test")

10. Get File attributes: Os.stat (file)

11. Modify file permissions and timestamps: Os.chmod (file)

12. Execute operating system command: Os.system ("dir")

13. Start a new process: Os.exec (), OS.EXECVP ()

14. Executing the program in the background: OSSPAWNV ()

15. Terminate the current process: Os.exit (), Os._exit ()

16. Detach file Name: Os.path.split (r "c:\python\hello.py")--("C:\\python", "hello.py")

17. Detach Extension: Os.path.splitext (r "c:\python\hello.py")--("C:\\python\\hello", ". Py")

18. Get path name: Os.path.dirname (r "c:\python\hello.py")--"C:\\python"

19. Get File Name: Os.path.basename (r "r:\python\hello.py")--"hello.py"

20. Determine if the file exists: os.path.exists (r "c:\python\hello.py")---True

21. Determine if absolute path: Os.path.isabs (r ". \python\")---False

22. Determine if it is a directory: Os.path.isdir (r "C:\python")--True

23. Determine if it is a file: Os.path.isfile (r "c:\python\hello.py")---True

24. Determine if it 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 directory: Os.path.walk ()

[2.shutil]

1. Copying individual files: shultil.copy (Oldfile, Newfle)

2. Copy Entire directory tree: Shultil.copytree (r ". \setup", R ". \backup")

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

[3.tempfile]

Copy the Code code as follows:


1. Create a unique temporary file: tempfile.mktemp ()---filename

2. Open temporary file: tempfile. Temporaryfile ()

[4.StringIO] #cStringIO是StringIO模块的快速实现模块

1. Create the memory file and write the initial data: F = Stringio.stringio ("Hello world!")

2. Read in memory file data: Print F.read () #或print f.getvalue ()--Hello world!

3. Want the memory file to write data: F.write ("Good day!")

4. Close the memory file: F.close ()

View Source code Printing Help

Copy the Code code as follows:


From time Import *

def secs2str (secs):
Return strftime ("%y-%m-%d%h:%m:%s", localtime (secs))

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

Outputs the specified Struct_time (default current time), based on the specified formatted string
Python format symbols in time Date:
%y Two-digit year representation (00-99)
%Y Four-digit year representation (000-9999)
%m Month (01-12)
One day in%d months (0-31)
%H 24-hour hours (0-23)
%I 12-hour hours (01-12)
%M minutes (00=59)
%s seconds (00-59)

%a Local Simplified Week name
%A Local Full week name
%b a locally simplified month name
%B Local Full month name
%c Local corresponding date representation and time representation
%j Day of the Year (001-366)
%p the equivalent of a local a.m. or p.m.
%u weeks of the year (00-53) Sunday is the beginning of the week
%w Week (0-6), Sunday for the beginning of the week
%W Week of the Year (00-53) Monday is the beginning of the week
%x Local corresponding date representation
%x Local corresponding time representation
%Z the name of the current time zone
Percent% of the number itself

9.strptime (...)
Strptime (string, format), Struct_time
Converts a time string to an array of time based on a specified format character
For example:
2009-03-20 11:45:39 The corresponding formatted string is:%y-%m-%d%h:%m:%s
Sat 28 22:24:24 2009 The corresponding formatted string is:%a%b%d%h:%m:%s%Y

10.time (...)
Floating point number, time ()
Returns the timestamp of the current time

Third, doubtful points
1. Daylight Saving Time
In Struct_time, daylight saving time seems to be useless, 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 represent daylight saving time and standard times, which convert to timestamps should be related to 3600, but the output will be 646585714.0 after conversion.

Four, small application
1.python Get current time
Time.time () gets the current timestamp
Time.localtime () struct_time form of the current time
Time.ctime () The string form of the current time

2.python formatted string
Formatted as 2009-03-20 11:45:39 in the form of
Copy the Code code as follows:


Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ()) formatted into Sat Mar 28 22:24:24 2009 Form

Time.strftime ("%a%b%d%h:%m:%s%Y", Time.localtime ()) 3. Convert a 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 detailed

Time module:
--------------------------
Time () #以浮点形式返回自Linux新世纪以来经过的秒数. 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 June 14 15:11:26 2006 '

Time.ctime ([sec]) #把秒数转换成日期格式, if no parameters are present, displays the current time.

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

>>> time.gmtime (os.path.getmtime (' e:\\untitleds.bmp '))
Time.struct_time (tm_year=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 a file's modification time to a date format (seconds to date)
>>> time.strftime ('%y-%m-%d%x ', Time.localtime (os.path.getmtime (' e:\\untitleds.bmp '))
' 2008-09-19 16:35:37 '

#定时3秒.
>>> Time.sleep (3)

Time Module Reference:
---------------------------------
#取一个文件的修改时间
>>> os.path.getmtime (' e:\\untitleds.bmp ')
1221813337.7626641

Variable
TimeZone the difference between the universal reconcile time and the local standard time, in seconds.
Altzone General coordination time and local daylight savings difference
Daylight flag, whether the local time reflects daylight savings.
Tzname (Standard Time zone name, Daylight Time zone name)
Function
Time () returns the number of seconds since the era to date with floating-point numbers.
Clock () returns the time at which the CPU starts the process with a floating-point number (or until the last time the function was called)
Sleep () Delays a number of seconds in floating-point numbers.
Gmtime () Converts a time in seconds to a universal Coordinated time sequence
LocalTime () converts seconds to local time series
Asctime () Converts a time series to a written description
CTime () Converts the second time to the written description
Mktime () converts a local time series into seconds
Strftime () Converts a sequence to a text description in the specified format
strptime () Resolves a time series from a text description in the specified format
Tzset () Change local time zone values

DateTime module
----------------------------
DateTime converts a date to seconds
-------------------------------------
>>> Import Datetime,time
>>> Time.mktime (Datetime.datetime (2009,1,1). Timetuple ())
1230739200.0

>>> cc=[2000,11,3,12,43,33] #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
-----------------
Demo calculation of two date difference days
>>> Import datetime
>>> D1 = Datetime.datetime (2005, 2, 16)
>>> D2 = Datetime.datetime (2004, 12, 31)
>>> (D1-D2). Days
47

Shows examples of calculation run times, displayed in seconds
Import datetime
StartTime = Datetime.datetime.now ()
#long Running
Endtime = Datetime.datetime.now ()
Print (endtime-starttime). seconds

Demonstrates the time to calculate the current time backwards by 10 hours.
>>> D1 = Datetime.datetime.now ()
>>> d3 = d1 + Datetime.timedelta (hours=10)
>>> D3.ctime ()

The classes used in this book are: DateTime and Timedelta two. They can be added and reduced between each other. Each class has some methods and properties to view the 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.