Home Backend Development Python Tutorial Instructions for using common functions in Python

Instructions for using common functions in Python

Mar 17, 2017 pm 04:26 PM
python

Basic customization

C.init(self[, arg1, ...]) constructor (with some optional parameters)

C.new(self[, arg1, ...]) Constructor (with some optional parameters); usually used to set subclasses of unchanged data types .

C.del(self) Deconstructor

C.str(self) Printable character output; built-in str() and print statement

C.repr(self) String output at runtime; 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) is object Define False value; built-in bool() (since version 2.2)

C.len(self) "Length" (can be used in classes); built-in len()

Special method Description

Object(value) comparisonc

C.cmp(self, obj) Object comparison; built-in cmp()

C.lt(self, obj) and less than/less than or equal to; corresponding to < and <= operators

C.gt(self, obj) and greater than/greater than or equal to ;corresponds to > and >= operators

C.eq(self, obj) and equal/not equal to;corresponds to ==,!= and <>operators

Attribute

C.getattr(self, attr) Gets the attribute; built-in getattr(); only called when the attribute is not found

C.setattr(self, attr, val) Set attribute

C.delattr(self, attr) Deleteattribute

C.getattribute(self, attr) Get attribute; Built-in getattr(); always called

C.get(self, attr) (descriptor) to get attributes

C.set(self, attr, val) (descriptor) Set attributes

C.delete(self, attr) (descriptor) Delete attributes

Custom class/simulation type

Numeric type : Binary operator

C.*add(self, obj) plus; + operator

C.*sub(self, obj) minus;-operator

C.*mul(self, obj) multiplication; *operator

C.*p(self, obj) division;/operator

C.*truep(self, obj) True division;/operator

C.*floorp(self, obj) Floor division;//operator

C.*mod(self, obj) modulo/remainder ;% operator

C.*pmod(self, obj) division and modulo; built-in pmod()

C.*pow(self, obj[, mod]) multiplication ;Built-in pow();**Operator

C.*lshift(self, obj) left shift;<

Special method description

Custom class/simulation type

Numeric type: binary operator

C.*rshift(self, obj) right shift; >>operator

C. *and(self, obj) bitwise AND; & operator

C.*or(self, obj) bitwise OR; | operator

C.*xor(self, obj ) bitwise AND or; ^ operator

Numeric type: unary operator

C.neg(self) one-yuan negative

C.pos(self) one-yuan positive

C.abs(self) absolute value; built-in abs()

C.invert(self) bitwise negation; ~ operator

Numeric type: numerical conversion

C.complex(self, com) is converted to complex (plural); built-in complex()

C.int(self) is converted to int; built-in int()

C.long(self) is converted to long; built-in long()

C.float(self) is converted to float; built-in float()

Numeric type: basic representation (String)

C.oct(self) octal representation; built-in oct()

C.hex(self) sixteen Base representation; built-in hex()

Numeric type: numerical compression

C.coerce(self, num) is compressed into the same numerical type; built-in coerce()

C.index(self)g When necessary, compress the optional numeric type to an integer type (for example: for slicing

Index, etc.

Sequence type

C.len(self) The number of items in the sequence

C.getitem(self, ind) Get 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

C.getslice(self, ind1, ind2) Get the sequence fragment

C.setslice(self, i1, i2,val) Set the sequence fragment

C.delslice(self, ind1,ind2) Delete the sequence fragment

C.contains(self, val) f test sequence member; built-in in keyword

C.*add(self,obj) concatenation; + operator

C.*mul (self,obj) Repeat; *operator

C.iter(self) Creates an iterative class; built-in iter()

Mapping type

C.len(self ) The number of items in mapping

C.hash(self) hash(hash)functionvalue

C.getitem(self,key) get given The value of a fixed key (key)

C.setitem(self,key,val) Set the value of a given key(key)

C.delitem(self,key) Delete a given key The value of (key)

C.missing(self,key) If the given key does not exist in the dictionary, a default value is provided

Remember a few commonly used onespythonFunction, lest you forget

Get file extension function: Return the extension and the file name path before the extension.

os.path.splitext('xinjingbao1s.jpg')

('xinjingbao1s', '.jpg')

os and os.path modules

os.listdir(dirname): List the directories and files under dirname

os.getcwd(): Get the current working directory

os.curdir: Return but the previous directory ('. ')

os.chdir(dirname): Change the working directory to dirname

os.path.isdir(name): Determine whether name is a directory. If name is not a directory, return false

os.path.isfile(name): Determine whether name is a file. If name does not exist, it will return false

os.path.exists(name): Determine whether file or directory name exists

os.path.getsize(name): Get the file size, if name is a directory, return 0L

os.path.abspath(name): Get the absolute path

os.path .normpath(path): Normalize path string form

os.path.split(name): Split file name and directory (in fact, if you use directories entirely, it will also treat the last directory as a file name, and it will not determine whether the file or directory exists)

os.path.splitext(): Separate the file name and extension

os.path.join(path,name ): Connect the directory to the file name or directory

os.path.basename(path): Return the file name

os.path.dirname(path): Return the 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 multi-level 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 under the last directory of the given path.

9. Delete a single directory: os.rmdir("test")

10. Get file attributes: 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. Execute the program in the background: osspawnv()

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

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

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

18. Get 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 it is an absolute path: os.path.isabs(r".\python\") --> False

22. Determine Whether it is a directory: os.path.isdir(r"c:\python") --> True

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

24. Determine whether it is a link file: os.path.islink(r"c:\python\hello.py") --> False

25. Get the 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]

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 the memory file data: print f.read() #or print f.getvalue() --> Hello world!

3. Write data to the memory file: f.write("Good day!")

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

View source code Print help 1 from time import *

2

3 def secs2str(secs):

4     return strftime("%Y-%m-%d %H:%M:%S",localtime(secs)) 5

5

6 >>> secs2str(1227628280.0)

7 '2008-11-25 23:51:20'

will The specified struct_time (default is the current time), according to the specified format string Output

Time and date formatting symbols in python:

%y two-digit Year representation (00-99)

%Y Four-digit year representation (000-9999)

%m Month (01-12)

%d Within the month Day in (0-31)

%H 24-hour hour (0-23)

%I 12-hour 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 complete month name

%c Local corresponding date representation and time representation

%j One day in the year (001-366)

%p The equivalent of local A.M. or P.M.

%U The number of weeks in the year (00-53) Sunday is the beginning of the week

%w The day of the week (0-6), Sunday is the beginning of the week

%W The number of weeks in the year (00-53) Monday is the beginning of the week

%x Local corresponding The date representation

%X The local corresponding time representation

%Z The name of the current time zone

%% The % number itself

9. strptime(…)

strptime(string, format) -> struct_time

Convert the time string into an array form according to the specified formatter Time

For example:

2009-03-20 11:45:39 The corresponding format string is: %Y-%m-%d %H:%M:%S

Sat Mar 28 22:24:24 2009 The corresponding format string is: %a %b %d %H:%M:%S %Y

10.time(…)

time() -> floating point number

Return the timestamp of the current time

3. Doubts

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 time respectively. The conversion between them into timestamps should be related to 3600, but after conversion The output is all 646585714.0

IV. Mini application

1.python gets the current time

time.time() gets the current timestamp

time.localtime () The struct_time form of the current time

time.ctime() The string form of the current time

2.python format string

Formatted into 2009-03-20 11:45:39Format

time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) formatted as Sat Mar 28 22:24: 24 2009 Form

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"))

Detailed explanation of python time datetime module

Time module:

------------------- -------

time() #Returns the number of seconds elapsed since the Linux new century in floating point form. 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 2006'

time.ctime([sec])#Convert seconds to date format. If there are no parameters, the current time will be displayed.

>>> import time

>>> time.ctime()

>>> 'Wed Jun 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 the modification time of a file 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'

#Timed for 3 seconds.

>>> time.sleep(3)

TIME module reference:

---------------- -------------------

#Get the modification time of a file

>>> os.path.getmtime('E :\\untitleds.bmp')

1221813337.7626641

Variable

timezone The difference between universal coordinated time and local standard time, in seconds.

altzone The difference between Universal Coordinated Time and local daylight saving time

daylight flag, whether local time reflects daylight saving time.

tzname (standard time zone name, daylight saving time zone name)

Function

time() returns the number of seconds since the epoch as a floating point number.

clock() returns the time when the CPU started this process as a floating point number, (or the time to the last time this function was called)

sleep() delays for a number of seconds expressed as a floating point number.

gmtime() Convert time expressed in seconds to universal coordinated time series

localtime() Convert seconds to local time series

asctime() Convert time series Convert to text description

ctime() Convert seconds to text description

mktime() Convert local time series to seconds

strftime() Convert seconds to seconds in the specified format Convert the sequence to a text description

strptime() Parse the time series from the text description in the specified format

tzset() Change the local time zone value

DateTime module

---------------------------------------------------------- ------------------------------------

>>> 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

-------- ---------

Demonstrate the calculation of the number of days difference between two dates

>>> import datetime

>>> d1 = datetime.datetime(2005, 2, 16)

>>> d2 = datetime.datetime(2004, 12, 31)

>>> (d1 - d2).days

47

Demonstrates an example of calculating the running time, displaying it in seconds

import datetime

starttime = datetime.datetime.now ()

#long running

endtime = datetime.datetime.now()

print (endtime - starttime).seconds

Demo calculation of the current time Go back 10 hours.

>>> d1 = datetime.datetime.now()

>>> d3 = d1 + datetime.timedelta(hours=10)

>>> d3.ctime()

The two commonly used classes are: datetime and timedelta. They can be added or subtracted from each other. Each class has some methods and properties to view specific values

The above is the detailed content of Instructions for using common functions in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles