Basic Custom Type
Copy Code code as follows:
C.__init__ (self[, arg1, ...]) builder (with some optional parameters)
C.__new__ (self[, arg1, ...]) constructor (with some optional parameters); typically used in a subclass that sets the invariant data type.
C.__del__ (self) deconstruction
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 an callable instance
C.__nonzero__ (self) defines a value of false for object; bool () (starting with version 2.2)
c.__len__ (self) length (available for Class); built Len ()
Special Method Description
Object (value) comparison C
Copy 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; corresponds to < and <= operators
C.__gt__ (self, obj) and greater than/greater than or equal to; corresponds to > and >= operators
C.__eq__ (self, obj) and equals/not equal to ==,!= and <> operators
Property
Copy Code code as follows:
C.__getattr__ (self, attr) gets the property; GetAttr (), which is called only if the property is not found
C.__setattr__ (self, attr, Val) set properties
C.__delattr__ (self, attr) Delete attribute
C.__getattribute__ (self, attr) get attributes; built getattr (); always called
C.__get__ (self, attr) (descriptor) Get Properties
C.__set__ (self, attr, Val) (descriptor) Setting properties
C.__delete__ (self, attr) (descriptor) Delete attribute
Custom class/Impersonation type
Numeric type: binary operator
Copy Code code as follows:
C.__*add__ (self, obj) plus; + operator
C.__*sub__ (self, obj) minus;-operator
C.__*mul__ (self, obj) multiplication; * 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/fetch remainder;% operator
C.__*divmod__ (self, obj) except and modulo; Divmod ()
C.__*pow__ (self, obj[, mod)) power; built-in POW (); * * operator
C.__*lshift__ (self, obj) left shift;<< operator
Special Method Description
Custom class/Impersonation type
Numeric type: binary operator
Copy Code code as follows:
C.__*rshift__ (self, obj) right-shift;>> operator
C.__*and__ (self, obj) bitwise AND;& operator
C.__*or__ (self, obj) bitwise OR; |
C.__*xor__ (self, obj) bitwise-with OR; ^ operator
Numeric type: unary operator
Copy Code code as follows:
c.__neg__ (self) unary negative
C.__pos__ (self) Unary positive
C.__abs__ (self) absolute value; built-in ABS ()
C.__INVERT__ (self) bitwise negation; ~ operator
Numeric type: Numeric conversions
Copy Code code as follows:
c.__complex__ (self, COM) to complex (plural); built-in complex ()
C.__int__ (self) to int; built int ()
C.__long__ (self) to long, built in long ()
C.__float__ (self) to float; built-in float ()
Numeric type: basic notation (String)
Copy Code code as follows:
C.__oct__ (self) octal, built-in Oct ()
c.__hex__ (self) hexadecimal representation; built-in Hex ()
Numeric type: Numeric compression
Copy Code code as follows:
C.__COERCE__ (self, num) compressed into the same numeric type; built coerce ()
C.__index__ (self) g when necessary, compresses the optional numeric type as an integer (for example: for slicing
Index and so on
Sequence type
[Code]
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) deletes a single sequence element
Special Method Description
Sequence type
Copy Code code as follows:
C.__getslice__ (self, ind1,ind2) get sequence fragments
C.__setslice__ (self, i1, i2,val) set sequence fragment
C.__delslice__ (self, ind1,ind2) deletes a sequence fragment
C.__contains__ (self, val) f test sequence members; built-in in keyword
C.__*ADD__ (self,obj) serial; + operator
c.__*mul__ (self,obj) repetition; * operator
C.__iter__ (self) creates an iteration class; built-in ITER ()
Mapping type
Copy Code code as follows:
Number of items in c.__len__ (self) mapping
C.__hash__ (self) hash (hash) function value
c.__getitem__ (Self,key) Gets the value of the given key (keys)
C.__SETITEM__ (self,key,val) Sets the value of the given key (keys)
c.__delitem__ (Self,key) deletes the value of the given key (the key)
C.__MISSING__ (Self,key) Given a key if it does not exist in the dictionary, a default value is provided
Remember a few common python functions, lest you forget
Get file name extension function: Returns the filename path before the extension and expansion.
Copy Code code as follows:
Os.path.splitext (' xinjingbao1s.jpg ')
(' Xinjingbao1s ', '. jpg ')
OS and Os.path modules
Copy Code code as follows:
Os.listdir (dirname): Listing directories and files under DirName
OS.GETCWD (): Get current working directory
Os.curdir: Return but front directory ('. ')
Os.chdir (dirname): Changing working directory to DirName
Os.path.isdir (name): Determines if name is a directory, name is not a directory returns false
Os.path.isfile (name): Determines whether name is a file, does not exist name also returns false
Os.path.exists (name): Determines whether a file or directory name exists
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 filename, and it will not determine whether the file or directory exists)
Os.path.splitext (): Detach file name and extension
Os.path.join (path,name): Connecting directories with file names or directories
Os.path.basename (PATH): Return file name
Os.path.dirname (path): Back to File path
1. Renaming: Os.rename (old, new)
2. Delete: Os.remove (file)
3. Listing files under the directory: Os.listdir (PATH)
4. Get the current working directory: OS.GETCWD ()
5. Change 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 properties: Os.stat (file)
11. Modify file permissions and timestamp: os.chmod (file)
12. Execute operating system command: Os.system ("dir")
13. Start a new process: Os.exec (), OS.EXECVP ()
14. In the background execution procedure: OSSPAWNV ()
15. Terminate the current process: Os.exit (), Os._exit ()
16. Separate 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 FileName: 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 it is an absolute path: Os.path.isabs (r ". \python\")--> False
22. Determine whether the directory: Os.path.isdir (r "C:\python")--> True
23. Judge whether it is a file: Os.path.isfile (r "c:\python\hello.py")--> True
24. Determine if the link 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 directory for all Files: Os.path.walk ()
[2.shutil]
1. Copy a single file: Shultil.copy (Oldfile, Newfle)
2. Copy the entire tree: Shultil.copytree (r ". \setup", R ". \backup")
3. Delete entire directory tree: Shultil.rmtree (r. \backup)
[3.tempfile]
Copy 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 into memory file data: Print F.read () #或print f.getvalue ()--> Hello world!
3. Write data to memory file: F.write ("Good day!")
4. Close Memory File: F.close ()
View Source code Printing Help
Copy 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 '
Converts the specified struct_time (the default current time) to the specified formatted string output
Time date format symbol in Python:
%y Two-digit year representation (00-99)
%Y Four-digit year representation (000-9999)
%m Month (01-12)
Day of%d months (0-31)
%H 24-hour hours (0-23)
%I 12 Hours of 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 number of weeks in a year (00-53) Sunday is the beginning of the week
%w Week (0-6), Sunday for the beginning of the week
%w number of weeks in a 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
%%% per se
9.strptime (...)
Strptime (string, format)-> Struct_time
Converts a time string to an array of times based on a specified format character
For example:
2009-03-20 11:45:39 The corresponding format string is:%y-%m-%d%h:%m:%s
Sat 28 22:24:24 2009 The corresponding format string is:%a%b%d%h:%m:%s%Y
10.time (...)
Time ()-> floating point number
Returns the time stamp for the current time
Third, doubt
1. Daylight Saving Time
Daylight saving time does not seem to be used in struct_time, 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 are converted to timestamps that should be related to 3600, but the output is 646585714.0 after conversion.
Four, small application
1.python Get current time
Time.time () Gets the current time stamp
Time.localtime () The Struct_time form of the current time
Time.ctime () The string form of the current time
2.python format string
Format into 2009-03-20 11:45:39 form
Copy Code code as follows:
Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ()) formatted as Sat 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]) #把秒数转换成日期格式, the current time is displayed if no arguments are taken.
>>> 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)
Converts a file's modification time to 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 Coordinated time and the local standard time, in seconds.
Altzone the difference between universal coordination time and local daylight savings
Daylight flag, whether local time reflects daylight savings.
Tzname (Standard Time zone name, Daylight Time zone name)
Function
Time () returns the number of seconds since the age of the era with floating-point numbers.
Clock () returns the time at which the CPU started the process with a floating-point number (or to the last time the function was called)
Sleep () Delays the number of seconds represented by floating-point numbers.
Gmtime () Converts the time in seconds to a universal Coordinated time sequence
LocalTime () converts seconds to local time sequence
Asctime () Converts a time series to a written description
CTime () Convert seconds to a written description
Mktime () Converts a local time sequence into seconds
Strftime () Converts a sequence to a text description in the specified format
Strptime () Parses a time series from a text description in a specified format
Tzset () Change 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=[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 sample
-----------------
Demonstrates calculation of two date difference days
>>> Import datetime
>>> D1 = Datetime.datetime (2005, 2, 16)
>>> D2 = Datetime.datetime (2004, 12, 31)
>>> (D1-D2).
47
Shows an example of the calculation run time, shown in seconds
Import datetime
StartTime = Datetime.datetime.now ()
#long Running
Endtime = Datetime.datetime.now ()
Print (endtime-starttime). seconds
Shows the time to calculate the current time back 10 hours.
>>> D1 = Datetime.datetime.now ()
>>> d3 = d1 + Datetime.timedelta (hours=10)
>>> D3.ctime ()
Its commonly used classes are: datetime and Timedelta two. They can add and subtract from each other. Each class has methods and properties to see the specific values