程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Introduction to 69 built-in functions (built-in functions) of python3.9 with simple and clear example code

編輯:Python

Python Built in interpreter ( The built-in ) There are many functions , This blog post introduces them one by one , Bloggers who feel it is necessary to give sample codes will give them .

Statement : Blogger ( Haohong image algorithm ) When writing this blog post , With Python Is the version number 3.9.10.

Official documents :https://docs.python.org/zh-cn/3.9/library/functions.html#built-in-functions

explain : The official documents list 14*5-1=59 Built in functions , But bloggers think classmethod、staticmethod、property These three are more like three keywords that define a class , Therefore, it is not introduced in this blog post , If you want to see the introduction of these three , Please refer to another blog post , link https://blog.csdn.net/wenhao_ir/article/details/125383895

This blog post repeatedly mentions the overview of iteratable objects , So what is an iteratable object ?
list 、 Tuples 、 Dictionaries and collections are typical iteratable objects , These objects all contain methods __iter__() or __next__(). The elements of an iteratable object can pass through its internal methods __iter__() or __next__() Traversal .

Catalog

  • 01- function abs(): Returns the absolute value of a number
  • 02- function all(): Determine whether all elements of the iteratable object are True
  • 03- function any(): Determine whether more than one element of the iteratible object is True
  • 04- function ascii(): Return any object ( character string 、 Tuples 、 List etc. ) Of ASCII Code printing ( Can be read ) edition
  • 05- function bin(): Returns the binary representation of an integer ( This binary representation is a string object )
  • 06- function bool(): Return object's bool value ( Boolean value )
  • 07- function breakpoint(): This function will cause the program to fall into the debugger when called
  • 08- function bytearray(): Returns a single byte array
  • 09- function callable(): Test whether the object can be called
  • 10- function chr(): Returns the specified unicode Character of code value
  • 11- function compile(): Compile string code into runnable code objects
  • 12- function complex(): The complex number is obtained by specifying the real and imaginary parts of the complex number
  • 13- function delattr(): Deletes the specified property or method from the specified object
  • 14- function dict(): Create a dictionary
  • 15- function dir(): Query the attributes of a class or an object ( Method ( Member functions )、 Variable ))
  • 16- function divmod(): Returns the quotient and remainder of division
  • 17- function enumerate(): Convert an iteratable object to an enumerated object
  • 18- function eval(): Execute function compile() Code object after
  • 19- function exec(): Execute function compile() Code object after
  • 20- function filter(): Filter out the unqualified elements in the iteratable object
  • 21- function float(): Converts an integer or string to a floating point number
  • 22- function format(): String formatting function
  • 23- function frozenset(): Returns a frozen iteratable object
  • 24- function getattr(): Get the value of a property of an object
  • 25- function globals(): Returns all global variables of the current running location of the program
  • 26- function hasattr(): Determine whether an object has a property
  • 27- function hash(): Get objects ( Usually the hash value of a character
  • 28- function help(): Used to view functions 、 class 、 Description of objects, etc
  • 29- function hex(): Returns the of a number 16 Hexadecimal said
  • 30- function id(): Return object's id( Memory address )
  • 31- function input(): Accept input data ( Tathagata comes from keyboard input ), return string type
  • 32- function int(): Convert a floating-point number or string to an integer
  • 33- function isinstance(): Determine whether an object is an instance of a class
  • 34- function issubclass(): Determine whether a class is a subclass of another class
  • 35- function iter(): Iterator object used to generate iteratable objects
  • 36 function len(): Returns the object ( character string 、 list 、 Tuples 、 Dictionaries 、 Collection etc. ) The length of
  • 37- function list(): Used to convert tuples or strings into lists
  • 38- function locals(): Returns the local variable of the current running position before the program
  • 39- function map(): Map an iteratable object to another iteratable object through a function
  • 40- function max(): Returns the maximum value of the given parameter
  • 41- function memoryview(): Returns the memory view object for the given parameter (memory view)
  • 42- function min(): Returns the minimum value for a given parameter
  • 43- function next(): Returns the next entry for the iterator
  • 44- function object(): Create an empty object
  • 45- function oct(): Converts an integer to 8 Base string
  • 46- function open(): Open a file , And return the file object
  • 47- function ord(): Return character's ASCII Number or Unicode The number
  • 48- function pow(): return x Of y The power is , The result can also be divided by the remainder
  • 49- function print(): Printout object
  • 50- function property(): obtain 、 Set up 、 Delete a property of a class
  • 51- function range(): Returns an iteratable object
  • 52- function repr(): String the object ( Textualization )【repr Should be return print Abbreviation 】
  • 53- function reversed(): Get the inverse iterator of the object ( The function is to reverse the iterator )
  • 54- function round(): Returns the rounded value of a floating-point number ( The number of decimal places can be controlled )
  • 55- function set(): Create a collection object
  • 56- function setattr(): Sets the property value of the object
  • 57- function slice(): Auxiliary slice operation
  • 58- function sorted(): Sort elements of iteratable objects
  • 59- function str(): Convert objects to string object ( String object )
  • 60- function sum(): Sum the iteratable objects
  • 61- function super(): Used to provide access to methods and properties of parent or sibling classes
  • 62- function tuple(): Convert iteratable objects to tuples
  • 63- function type(): Returns the type of the object
  • 64- function vars(): Returns the \_\_dic\_\_ attribute
  • 65- function zip(): Packaging multiple iteratible objects
  • 66- function \_\_import\_\_(): The import module 、 Script 、 Classes and functions, etc

01- function abs(): Returns the absolute value of a number

abs(x)
Returns the absolute value of a number . Parameters can be integers 、 Floating point numbers or anything that implements __abs__() The object of . If the parameter is a complex number , Returns its module .
This example code is not given .

02- function all(): Determine whether all elements of the iteratable object are True

What is an iteratable object ? list 、 Tuples 、 Dictionaries and collections are typical iteratable objects , These objects all contain methods __iter__() and __next__(). The elements of an iteratable object can pass through its internal methods __iter__() and __next__() Traversal .
So what condition does the element object satisfy True Well ? Please refer to another blog post https://blog.csdn.net/wenhao_ir/article/details/125439660

Be careful : According to the truth , An empty tuple 、 The Boolean value of the empty list is False, So for empty tuples 、 An empty list , function all() Should return to False That's right , But that's not the case , For empty tuples 、 Empty list function all() The return value of is also True, Special attention should be paid to this point .
The sample code is as follows :

list1 = [1, 2, 3]
list2 = [-1, 2, 3]
list3 = [0, 2, 3]
list4 = []
bool1 = all(list1)
bool2 = all(list2)
bool3 = all(list3)
bool4 = all(list4)

The operation results are as follows :

03- function any(): Determine whether more than one element of the iteratible object is True

What is an iteratable object ? list 、 Tuples 、 Dictionaries and collections are typical iteratable objects , These objects all contain methods __iter__() and __next__().

any() Function is used to determine whether more than one element of an iteratable object is True, If I have a theta True, Then return to True; If it's all False, Then return to False.

So what condition does the element object satisfy True Well ? Please refer to another blog post https://blog.csdn.net/wenhao_ir/article/details/125439660

Be careful : For the function any() for , An empty tuple 、 The empty list returns a value of False.

The sample code is as follows :

list1 = [0, '', False, None]
list2 = [-1, 2, 3]
list3 = [0, 2, 3]
list4 = []
bool1 = any(list1)
bool2 = any(list2)
bool3 = any(list3)
bool4 = any(list4)

The operation results are as follows :

04- function ascii(): Return any object ( character string 、 Tuples 、 List etc. ) Of ASCII Code printing ( Can be read ) edition

function ascii() Return any object ( character string 、 Tuples 、 List etc. ) A readable version of , It's a bit like casting an object to ASCII Code string , It will not ASCII Replace character with escape character .
The above sentence is not easy to understand , Just look at a sample code .

The sample code is as follows :

x1 = ascii('My name is Ståle')
print(x1)
x2 = ascii([77, 88, 'swh'])
print(x2)

The operation results are as follows :


Pay attention here x1 Medium “\xe5” What's going on? ? That's because of ASCII There are no characters in the code å , So I replaced it with \xe5
in addition , We see that the quotation marks before and after the string are also converted into characters .

05- function bin(): Returns the binary representation of an integer ( This binary representation is a string object )

The sample code is as follows :

x1 = bin(10)
print(x1)

The operation results are as follows :

06- function bool(): Return object's bool value ( Boolean value )

About functions bool(), See my other blog post https://blog.csdn.net/wenhao_ir/article/details/125439660

07- function breakpoint(): This function will cause the program to fall into the debugger when called

This function is 3.7 Only after version , The frequency of use is not high , Don't introduce too much for the time being .

08- function bytearray(): Returns a single byte array

function bytearray() The grammar is as follows :

bytearray([source[, encoding[, errors]]])

Parameter Introduction :
If source Integers , Returns a length of source Initialize the array of ;
If source For the string , As specified encoding Converts a string to a sequence of bytes ;
If source Is an iterable type , Because each element has only one byte of storage space , The element must be [0 ,255] The integer ;
If no parameters are entered , The default is to initialize the array as 0 Elements .
The sample code is as follows :

bytearray0 = bytearray()
bytearray1 = bytearray(5)
bytearray2 = bytearray('suwenhao', 'utf-8')
bytearray3 = bytearray([65, 66, 67])

The operation results are as follows :

From the above results, we can see :
① The length is source The default value of the elements of the initialization array of is \x00
② The display is in ASCII Code to display its value , therefore bytearray3 The three numbers of are displayed as capital letters ABC.

09- function callable(): Test whether the object can be called

If the specified object is callable , Then return to True, Otherwise return to False.
Be careful : If the function callable() return True,object The call may still fail ; But if you go back False, Call object object It will never work .
For the function 、 Method 、lambda Anonymous functions 、 Class and implementation __call__ Class instance of a method , It will all return True.
The sample code is as follows :

def add(a_p, b_p):
return a_p + b_p
class A:
def method(self):
return 0
class B:
def __call__(self):
return 0
bool1 = callable(0) # object 0 Cannot be called , So we should go back to False
bool2 = callable(add) # function add return True
bool3 = callable(A) # class A return True
a = A()
bool4 = callable(a) # class A Instantiate the object a It didn't come true __call__, So we should go back to False
bool5 = callable(B) # class B return True
b = B()
bool6 = callable(b) # class B Instantiate the object b Realized __call__, So we should go back to True

The operation results are as follows :

10- function chr(): Returns the specified unicode Character of code value

function chr( i ) return Unicode The code point is an integer i The character string format of . for example ,chr(97) Return string ‘a’,chr(8364) Return string ‘€’.

i — It can be 10 Base can also be 16 A number in the form of decimal , The numerical range is 0 To 1,114,111 (16 Into the system for 0x10FFFF).

The sample code is as follows :

char1 = chr(97)
char2 = chr(8364)

The operation results are as follows :

in addition , Available functions ord() Return character's ASCII Number or Unicode The number , For details, see section 47 A function .

11- function compile(): Compile string code into runnable code objects

function compile() To compile string code into runnable code objects .
After reading the above sentence, I usually don't know what it did . No problem , Just look at the sample code .
The sample code is as follows :

a1 = 188
x = compile('print(a1)', 'jhoij', 'eval')
eval(x)

The operation results are as follows :


From the example code above, we can see , When a statement print(a1) Implemented in the form of eval Of compile After the operation , Got the object x, Use at this time eval() Function call object x, It is equivalent to executing the statement print(a1).

What's the point of such an operation ?
I found an opinion on the Internet as follows :
When executing code in string form , Each time, the code must be byte compiled .compile() Function provides one-time byte code precompiling , Every time you call in the future , No need to compile .
But bloggers ( Haohongjun ) I think there is something wrong with this statement , From the example above , Each time I run this script, I will execute it again compile() function , That's why I compile it every time , Unless its results are cached somewhere .

compile() The function syntax is as follows :

compile(source, filename, mode[, flags[, dont_inherit,[ optimize]]])

The meaning of the parameter is as follows :

12- function complex(): The complex number is obtained by specifying the real and imaginary parts of the complex number

The plural is Python A type of numeric value in . You can use functions complex() The complex number is obtained by specifying the real and imaginary parts of the complex number .
The sample code is as follows :

z1 = complex(7, 8)
print(z1)

The operation results are as follows :

13- function delattr(): Deletes the specified property or method from the specified object

The grammar is as follows :

delattr(object, name)

object – object .
name – It must be the property of the object .
The sample code is as follows :

class Coordinate:
x = 10
y = -5
z = 0
point1 = Coordinate()
print('x = ', point1.x)
print('y = ', point1.y)
print('z = ', point1.z)
delattr(Coordinate, 'z')
print('-- Delete z After attribute --')
print('x = ', point1.x)
print('y = ', point1.y)
# Trigger error 
print('z = ', point1.z)

The operation results are as follows :

14- function dict(): Create a dictionary

function dict() For details, please refer to the blog https://blog.csdn.net/wenhao_ir/article/details/125412774 Of “01- attach 2”

15- function dir(): Query the attributes of a class or an object ( Method ( Member functions )、 Variable ))

function dir() For details, please refer to the blog https://blog.csdn.net/wenhao_ir/article/details/125421060

16- function divmod(): Returns the quotient and remainder of division

The sample code is as follows :

result_1 = divmod(5, 2)

The operation results are as follows :

17- function enumerate(): Convert an iteratable object to an enumerated object

About functions enumerate() Detailed introduction , See my other blog post :https://blog.csdn.net/wenhao_ir/article/details/125443427

18- function eval(): Execute function compile() Code object after

For more information, see the function compile() Introduction to , Specifically, it is the... In this blog post 11 individual .

19- function exec(): Execute function compile() Code object after

20- function filter(): Filter out the unqualified elements in the iteratable object

filter() Function to filter the sequence , Filter out the elements that do not meet the conditions , Returns an iterator object , If you want to convert to a list , have access to list() To convert .

This accepts two parameters , The first one is a function , The second is the sequence , Each element of the sequence is passed to the function as a parameter to be judged , Then return True or False, And then it will return True Is placed in the new list .

The sample code is as follows :

def is_odd(n):
return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)

The operation results are as follows :

This function is related to the list (list) Methods sort() The first parameter of key The use of is quite similar , See the blog for details https://blog.csdn.net/wenhao_ir/article/details/125406092

21- function float(): Converts an integer or string to a floating point number

what ? Strings can also be converted to floating point numbers , Yes , You read that right , Just look at the example below .

int1 = 112
str1 = '123'
float_1 = float(int1)
float_2 = float(str1)

The operation results are as follows :

From the above results, we can see , character string ’123’ Converted to floating point numbers 123.0, This is it. Python The flexibility of , Same function , stay C++ Class is required in stringstream To achieve , For details, see my other blog post https://blog.csdn.net/wenhao_ir/article/details/124508457

22- function format(): String formatting function

About functions format(), I have been blogging https://blog.csdn.net/wenhao_ir/article/details/125390532 I have described in detail in , I won't repeat it here .

23- function frozenset(): Returns a frozen iteratable object

function frozenset() Used to return a frozen iteratable object from the original iteratable object , An iteratable object that is frozen cannot add or remove any elements .
The sample code is as follows :

list1 = ['Google', 'CSDN', 'tencent', 1997, 1999, 1998]
list2 = frozenset(list1)
list2[0] = 'facebook'

The operation results are as follows :

24- function getattr(): Get the value of a property of an object

The sample code is as follows :

class A(object):
bar = 1
a1 = A()
b1 = getattr(a1, 'bar')

The operation results are as follows :

If you want to set the property value of an object , You can use functions setattr() Let's set it up ! function setattr() See article of this blog 56 A function

25- function globals(): Returns all global variables of the current running location of the program

globals() The function returns all global variables in the current location as a dictionary type .
The sample code is as follows :

str1 = 'suwenhao'
int1 = 1990
list1 = [1, 2, 3]
global_variable = globals()

The operation results are as follows :

26- function hasattr(): Determine whether an object has a property

function hasattr() The sample code of is as follows :

class Coordinate:
x = 10
y = -5
z = 0
point1 = Coordinate()
bool1 = hasattr(point1, 'x')
bool2 = hasattr(point1, 'y')
bool3 = hasattr(point1, 'z')
bool4 = hasattr(point1, 'no') # No attribute 

The operation results are as follows :

27- function hash(): Get objects ( Usually the hash value of a character

The sample code is as follows :

hash1 = hash('swh')
hash2 = hash(2487872782)

Run the above code twice , The results are as follows :
The results of the first run :

The result of the second run :

From the above two running results, we can see , A string of hash Values are not unique , The integer hash Value is itself .

28- function help(): Used to view functions 、 class 、 Description of objects, etc

The sample code is as follows :

help('sys') # see sys Module help 
help('str') # see str Class help 
a = [1, 2, 3]
help(a) # view list list With the help of the 
help(a.append) # see list Of append Method help 

The next two lines of code

a = [1, 2, 3]
help(a.append) # see list Of append Method help 

The results are as follows :

29- function hex(): Returns the of a number 16 Hexadecimal said

The sample code is as follows :

hex1 = hex(10)

The operation results are as follows :

Be careful : function hex() It returns a string object .

30- function id(): Return object's id( Memory address )

The sample code is as follows :

str1 = 'CSDN'
id1 = id(str1)

The operation results are as follows :

31- function input(): Accept input data ( Tathagata comes from keyboard input ), return string type

The sample code is as follows :

str1 = input("input:")

The operation results are as follows :
First run ( Input string ):




Second operation ( Input number )


From the results of the second run, we can see , The input number is also treated as a string . But it doesn't matter , We can use functions float() Or functions int() Converts a string number to float The type and int Type .

32- function int(): Convert a floating-point number or string to an integer

The grammar is as follows :

int(x, base=10)

Parameter meaning :
x – String or number .
base – representative x Which base number is it , Note that it doesn't mean that the decimal value of return

The sample code is as follows :

int1 = int(3.6)
int2 = int('20')
int3 = int('12', 16) #16 It's binary 12 The conversion 10 Into the system is 18
int4 = int('0xa', 16)

The operation results are as follows :

From the above running results, we can see that , function int() When converting floating-point numbers to integers , The decimal part is directly discarded , Rather than rounding .

33- function isinstance(): Determine whether an object is an instance of a class

The sample code is as follows :

a = 2
bool1 = isinstance(a, int)
bool2 = isinstance(a, str)
bool3 = isinstance(a, (str, int, list)) # As long as it is one of the tuples, it returns True

The operation results are as follows :

34- function issubclass(): Determine whether a class is a subclass of another class

The grammar is as follows :

issubclass(class1, class2)

If class1 yes class2 Subclass returns True, Otherwise return to False.
The sample code is as follows :

class A:
pass
class B(A):
pass
class C:
pass
bool1 = issubclass(B, A)
bool2 = issubclass(B, C)

The operation results are as follows :

35- function iter(): Iterator object used to generate iteratable objects

This function is used to generate iterator objects for iteratable objects . With list Object as an example , If we want to iterate through it , How to operate ? One way is to make the iterator object , Then use the built-in function next() Traverse .

Built in functions next() The grammar is as follows :

next(iterable[, default])

iterable – Iteratable object
default – Optional , Set to return the default value when there is no next element , If not set , No next element will trigger StopIteration abnormal .

Let's look at functions iter() The grammar of :

iter(object[, sentinel])

Depending on whether there is a second argument , The first argument is interpreted very differently .
If there is no second argument ,object Must support iterative protocols ( Yes __iter__() Method ) Collection object for ( Such as the list 、 Tuples 、 All sets have __iter__() Methodical , post https://blog.csdn.net/wenhao_ir/article/details/125421060 The running results of the first example code of the ), Or must support sequence protocols ( Yes __getitem__() Method , And the numerical parameters are from 0 Start ). If it does not support these protocols , Will trigger TypeError.
If there is a second argument sentinel, that object Must be a callable object . The iterator generated in this case , Each iteration calls its __next__() Methods are called without arguments object; If the result is sentinel The trigger StopIteration, Thus stopping the iteration , Otherwise, the result of the call is returned ..
fit iter() One of the applications of the second form of is the building block reader . for example , Read fixed width blocks from binary database files , Until you reach the end of the file , An example of this case is as follows :

from functools import partial
with open('mydata.db', 'rb') as f:
for block in iter(partial(f.read, 64), 'b'):
process_block(block)

The function above partial() Will be iterated down without parameters , Until its return value is ’b’ Just stop iterating .

Back to the first case , Using functions iter() And the function next() The sample code to iterate over the list is as follows :

x = iter(["apple", "banana", "cherry"])
print(next(x))
print(next(x))
print(next(x))

The operation results are as follows :

36 function len(): Returns the object ( character string 、 list 、 Tuples 、 Dictionaries 、 Collection etc. ) The length of

This is about the string 、 list 、 Tuples 、 Dictionaries 、 Collection has been introduced , See the link below for details :
https://blog.csdn.net/wenhao_ir/article/details/125396412( In this blog post, the 14-3 Point used len() Measure string length )
https://blog.csdn.net/wenhao_ir/article/details/125400072
https://blog.csdn.net/wenhao_ir/article/details/125407815
https://blog.csdn.net/wenhao_ir/article/details/125412774
https://blog.csdn.net/wenhao_ir/article/details/125424671
So here are no more examples .

37- function list(): Used to convert tuples or strings into lists

The sample code is as follows :

tup1 = ('Google', 'Taobao', 'CSDN', 555)
list1 = list(tup1)
str1 = "Hello World"
list2 = list(str1)

The operation results are as follows :

Correlation function :
62- function tuple(): Convert iteratable objects to tuples

38- function locals(): Returns the local variable of the current running position before the program

locals() The function returns all local variables in the current position as dictionary type .
The sample code is as follows :

def fun1(arg): # Two local variables :arg、z
z = 1
print(locals())
fun1(6)

The operation results are as follows :

39- function map(): Map an iteratable object to another iteratable object through a function

map() Function will map the specified sequence according to the function provided . Its first parameter and list Methods sort()、filter() The first argument to the function uses something like .
sort() For a detailed introduction to the method, see the blog https://blog.csdn.net/wenhao_ir/article/details/125406092
filter() The function has been introduced above .

Example code 1 is as follows :

def square(x): # Calculate the square number 
return x ** 2
iter1 = map(square, [1, 2, 3, 4, 5])
list1 = list(iter1)

The operation results are as follows :

Example code 2 is as follows ( Anonymous functions ):

iter1 = map(lambda x: x ** 3, [1, 2, 3, 4, 5])
list1 = list(iter1)

The operation results are as follows :

40- function max(): Returns the maximum value of the given parameter

This function before the string 、 list 、 Tuples are mentioned in the introduction , In a string, it appears as a method of a character class , But it can also work on string objects .

Here is a comprehensive example code .

str1 = 'abcdef'
max_str1 = max(str1)
list1 = [10, 11, 12, 13]
max_list1 = max(list1)
tup1 = (20, 21, 22, 25)
max_tupl1 = max(tup1)
set1 = {
50, 51, 52, 53}
max_set1 = max(set1)

The operation results are as follows :

41- function memoryview(): Returns the memory view object for the given parameter (memory view)

So called memory view object , Wrap the data that supports the buffer protocol , You can then view by byte .
The sample code is as follows :

v = memoryview(bytearray("abcefg", 'utf-8'))
v_01 = v[1]
v_02 = v[2]

The operation results are as follows :

I feel like Pycharm-IDE This function is not very important , Because I'm here IDE It is very convenient to view the memory of objects in .

42- function min(): Returns the minimum value for a given parameter

function min() With the first 40 individual max() It's as like as two peas , It just returns the minimum value , So I won't introduce it here , No more sample code .

43- function next(): Returns the next entry for the iterator

function next() Introducing 35- function iter() I have already introduced , I won't go into it here .

44- function object(): Create an empty object

object() Function returns an empty object .
You cannot add new properties or methods to this object , This function takes no arguments .
This object is the foundation of all classes , It has default built-in properties and methods for all classes .
The sample code is as follows :

x = object()

The operation results are as follows :

45- function oct(): Converts an integer to 8 Base string

function oct() Converts an integer to 8 Base string ,8 Base with 0o As a prefix .
The sample code is as follows :

str1 = oct(10)

The running results are as follows :

46- function open(): Open a file , And return the file object

open() Function to open a file , And return the file object , This function is used for processing files , If the file cannot be opened , Will throw out OSError.
Be careful : After the file object is used , Be sure to call close() Function close file .
open() A common form of a function is to take two arguments : file name (file) And pattern (mode).

open(file, mode='r')

The complete syntax format is as follows :

pen(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

file— The path or name of the file .
mode— File open mode , The details are as follows :


Additional explanation :
mode Is an optional string , Used to specify the mode for opening files .
The default value is ‘r’ , And ‘rt’ Synonymous , This means that it opens and reads the file in text mode .
Other common patterns are : write in ‘w’ 、 Exclusive creation ‘x’ 、 Additional writing ‘a’( stay some Unix On the system , No matter where the current file pointer is , all Writes are appended to the end of the file ).

Next, let's move on to functions open() Other parameters of .
In text mode , If encoding Is not specified , The coding used depends on the platform : Use locale.getpreferredencoding(False) To get the local code .
To read and write raw bytes , Please use binary mode and do not specify encoding.
Files opened in binary mode ( Include mode In the parameter ‘b’ ) The content returned is bytes object , No decoding . In text mode ( By default , Or in mode Parameter contains ‘t’ ) when , The contents of the file are returned as str , First use the specified encoding ( If a given ) Or use the default byte encoding and decoding of the platform .

Pattern ‘w+’ And ‘w+b’ Will open the file and empty the contents .
Pattern ‘r+’ And ‘r+b’ Will open the file without emptying the contents .

buffering— This parameter is used to set the buffer .

encoding— encoding Is the name of the encoding used to decode or encode the file , In general use utf8. This should only be used in text mode . The default encoding is platform dependent ( Regardless of locale.getpreferredencoding() What value is returned ), But you can use any Python Supported by text encoding . For a list of supported encodings , see also Pythoncodecs modular .

errors– Is an optional string parameter , Specifies how encoding and decoding errors are handled - This cannot be used in binary mode . Various standard error handlers can be used ( Listed in Error handling scheme ), But use codecs.register_error() Any error handling name registered is also valid . Standard names include :

  • ‘strict’: If there is a coding error ,‘strict’ May trigger ValueError abnormal , The default value is None Have the same effect .
  • ‘ignore’: Ignore mistakes . Please note that , Ignoring coding errors can result in data loss .
  • ‘replace’ : The replacement tag is ( for example ‘?’ ) Insert where there is wrong data .
  • ‘surrogateescape’: Any incorrect bytes will be represented as U+DC80 to U+DCFF Substitute code point below the range . Use when writing data surrogateescape When the handle is handled incorrectly, these alternate code points will be returned to the same bytes . This applies to files with unknown encoding formats .
  • ‘xmlcharrefreplace’: Only supported when writing to a file ‘xmlcharrefreplace’. Characters that are not supported by encoding will be replaced with the corresponding XML Character reference &#nnn;
  • ‘backslashreplace’ : use Python Replace malformed data with the reverse escape sequence of .
  • ‘namereplace’ ( It only supports ) use \N{…} Escape sequence replaces unsupported characters .

newline— Control the line wrapping of the file , namely universal newlines How the model works ( It applies only to text mode ). It can be None,‘’,‘\n’,‘\r’ and ‘\r\n’. It works as follows :
When reading input from a stream , If newline by None, Then enable the general line feed mode . The lines in the input can be in the form of ‘\n’,‘\r’ or ‘\r\n’ ending , These lines are translated into ‘\n’ Before returning to the caller . If it is ‘’, Then enable the general line feed mode , But the end of the line will be returned to the caller untranslated . If it has any other legal value , Then the input line is terminated only by the given string , And the end of the line will be returned to the caller who did not call .
When writing output to stream , If newline by None, Then write any ‘\n’ All characters will be converted to the system default line separator os.linesep. If newline yes ‘’ or ‘\n’, No translation . If newline Is any other legal value , Then write any ‘\n’ The character will be converted to the given string .

closefd— If closefd yes False And give the file descriptor instead of the file name , So when the file is closed , The underlying file descriptor will remain open . If the file name is given, then closefd It has to be for True ( The default value is ), Otherwise, an error will be raised .

opener— You can pass callable opener To use a custom opener . Then by using parameters ( file,flags ) call opener Gets the base file descriptor of the file object . opener Must return an open file descriptor ( Use os.open as opener Time and transmission None The effect is the same ).

47- function ord(): Return character's ASCII Number or Unicode The number

ord() The function is chr() Function for 8 Bit ASCII character string ) The pairing function of [ function chr() See Chapter... Of this article 10 individual ], It takes a string (Unicode character ) As a parameter , Return the corresponding ASCII The number , perhaps Unicode The number .
The sample code is as follows :

int1 = ord('a')
char1 = chr(int1)

The operation results are as follows :

48- function pow(): return x Of y The power is , The result can also be divided by the remainder

The grammar is as follows :

pow(x, y[, z])

Calculation x Of y Power , If z In existence , Then we take the model of the result , The result is equivalent to pow(x,y) %z

The sample code is as follows :

int1 = pow(2, 3)
int2 = pow(2, 3, 6)

The operation results are as follows :

49- function print(): Printout object

function print() See my other blog post for a detailed introduction to :https://blog.csdn.net/wenhao_ir/article/details/125390532

50- function property(): obtain 、 Set up 、 Delete a property of a class

function property() Usually used to get 、 Set up 、 Delete a property of a class .

function property() The grammar is as follows :

class property([fget[, fset[, fdel[, doc]]]])

Parameters :
fget – - Gets the value of the property ( The function of a function is not necessarily to get the property value , This is easy to understand after reading the sample code )
fset — A function that sets the value of a property ( The function of a function does not necessarily set the property value , This is easy to understand after reading the sample code )
fdel — Deletes the attribute value function ( The function of a function does not necessarily delete attributes , This is easy to understand after reading the sample code )
doc — Attribute description information .

The sample code is as follows :

class C(object):
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")

If c yes C Instantiation , be
c.x Will call getx(),
c.x = value Will call setx()
del c.x Will call delx()
If a given doc Parameters , It will become the value of this property docstring, otherwise property The function will copy fget Functional docstring( If any ).

Continue to refine the sample code as follows :

# Blogger WeChat /QQ 2487872782
# If you have any questions, you can contact the blogger 
class C(object):
def __init__(self):
self._x = 100
self._y = 200
def getx(self):
print('called getx and x={}'.format(self._x))
def setx(self, value):
self._x = value
print('called setx and x={}'.format(self._x))
def delx(self):
del self._x
print('called delx')
def gety(self):
print('called gety and y={}'.format(self._y))
def sety(self, value):
self._y = value
print('called sety and y={}'.format(self._y))
def dely(self):
del self._y
print('called dely')
x = property(getx, setx, delx, "I'm the 'x' property.")
y = property(gety, sety, dely, "I'm the 'y' property.")
c = C()
c.x
c.x = 12
del c.x
c.y
help(c)

The operation results are as follows :


In the above code, I defined two and functions property() Related attribute names , Respectively x and y, And I also for x and y Three functions are set , With x For example , These three functions pass through
c.x
c.x = 12
del c.x
To call .

51- function range(): Returns an iteratable object

Be careful :
Python3 range() Function returns an iteratable object , Not list objects , You can use functions list() Convert it to a list .
Python2 range() The function returns a list .
The grammar is as follows ( There are two forms ):
range(stop)
range(start, stop[, step])
start— Count from start Start . The default is 0 Start . for example range(5) Equivalent to range(0, 5);
stop:— Count to stop end , But does not include stop. for example :range(0, 5 yes [0, 1, 2, 3, 4], Note that... Is not included 5.
step— step , The default is 1. for example :range(0, 5) Equivalent to range(0, 5, 1)

The sample code is as follows :

rang1 = range(5)
list1 = list(rang1)
for i in range(1, 4, 1):
print(i)

The operation results are as follows :

52- function repr(): String the object ( Textualization )【repr Should be return print Abbreviation 】

The sample code is as follows :

dict1 = {
'name': 'suwenhao', 'likes': 'reading', 123: 456}
str1 = repr(dict1)
print(str1)
list1 = ['Google', 'CSDN', 1997, 1999]
str2 = repr(list1)
print(str2)

The operation results are as follows :

The sample code is as follows :

Built in functions str() Similar to this function , function str() For an introduction to 59 spot .

53- function reversed(): Get the inverse iterator of the object ( The function is to reverse the iterator )

The sample code is as follows :

str1 = 'abcdefg'
str1_reverse = reversed(str1)
str1_reverse_list = list(str1_reverse)
list1 = [1, 2, 3, 4, 5]
list1_reverse = reversed(list1)
list1_reverse_list = list(list1_reverse)
tup1 = ('A', 'B', 'C', 'D')
tup1_reverse = reversed(tup1)
tup1_reverse_list = list(tup1_reverse)

The results are shown in the following figure :

54- function round(): Returns the rounded value of a floating-point number ( The number of decimal places can be controlled )

The grammar is as follows :

round( x [, n] )

Parameter meaning :
x — Floating point number to be processed .
n — Indicates the number of decimal places to be reserved , The default value is 0, That is, the decimal part is not retained .

Be careful : It does the approximate operation of rounding , Rather than rounding , Just look at the following example code .

The sample code is as follows :

print("round(70.3) : ", round(70.3))
print("round(70.4) : ", round(70.4))
print("round(70.5) : ", round(70.5))
print("round(70.6) : ", round(70.6))
print("round(70.7) : ", round(70.7))
print("round(80.23, 1) : ", round(80.23, 1))
print("round(80.24, 1) : ", round(80.24, 1))
print("round(80.25, 1) : ", round(80.25, 1))
print("round(80.26, 1) : ", round(80.26, 1))
print("round(80.27, 1) : ", round(80.27, 1))

The operation results are as follows :

55- function set(): Create a collection object

function set() In Bowen https://blog.csdn.net/wenhao_ir/article/details/125424671 Has been introduced in , I won't repeat it here .

56- function setattr(): Sets the property value of the object

function setattr() The corresponding function getattr(), Used to set property values , This attribute does not necessarily exist .
The grammar is as follows :

setattr(object, name, value)

The meaning of the parameter is as follows :
object – object .
name – character string , Object properties .
value – Property value
The sample code is as follows :

class A(object):
bar = 1
a = A()
bar1 = getattr(a, 'bar') # get attribute bar Value 
setattr(a, 'bar', 5) # Set the object a Properties of bar Value 
bar2 = getattr(a, 'bar') # Get the properties again bar Value 

The operation results are as follows :

57- function slice(): Auxiliary slice operation

slice() Function to implement slicing objects , It is mainly used for parameter passing in slice operation function .
The grammar is as follows :
There are two forms :

slice(stop)
slice(start, stop[, step])

Parameter meaning :
start – Starting index value
stop – End index value
step – Index spacing

The sample code is as follows :

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
slice1 = slice(5)
list_sub1 = list1[slice1]
slice2 = slice(1, 8, 2)
list_sub2 = list1[slice2]

The operation results are as follows :

Here's an analysis of list_sub2 How did you get ?
Index range is [1, 8) Notice that it's left closed right open .
The index step is 2, Then the valid index value is 1、1+2=3、3+2=5、5+2=7
Index value 1、3、5、7 The corresponding element values are :10、40、60、80
therefore list_sub2 by [20, 40, 60, 80]
Of course , We don't usually use this slice object , Instead, write the slice expression directly ,
That is, we usually put the sentence :

slice2 = slice(1, 8, 2)
list_sub2 = list1[slice2]

It's written in :

list_sub2 = list1[1:8:2]

58- function sorted(): Sort elements of iteratable objects

function sorted() And methods in the list sort() The usage and functions of the are basically the same .
The difference is that the function sorted() You can sort all iteratable object elements , And it will return a new list . And the methods in the list sort() It can only be used for lists , And operate on the original list object .
So there is no longer a function here sorted() Introduced , You can refer to my other blog post https://blog.csdn.net/wenhao_ir/article/details/125400072 pass the civil examinations 16 Point to point method sort() Introduction to .

59- function str(): Convert objects to string object ( String object )

Built in functions repr() Similar to this function , function repr() For an introduction to 52 spot .
The sample code is as follows :

dict1 = {
'name': 'suwenhao', 'likes': 'reading', 123: 456}
str1 = str(dict1)
print(str1)
list1 = ['Google', 'CSDN', 1997, 1999]
str2 = str(list1)
print(str2)

The operation results are as follows :


Built in functions repr() Similar to this function , function repr() For an introduction to 52 spot .

60- function sum(): Sum the iteratable objects

The grammar is as follows :

sum(iterable, start)

The meaning of the parameter is as follows :
iterable— It's necessary . Iteratable objects for requirements and ( Sequence ).
start— Optional . The value added to the return value .
The sample code is as follows :

resutl1 = sum([0, 1, 2])
result2 = sum((2, 3, 4), 1) # The tuple object calculates the sum and adds 1
result3 = sum([0, 1, 2, 3, 4], 2) # Add the list after calculating the sum 2

The operation results are as follows :

61- function super(): Used to provide access to methods and properties of parent or sibling classes

A detailed introduction to this function , You can see another blog post of mine :https://blog.csdn.net/wenhao_ir/article/details/125472478

62- function tuple(): Convert iteratable objects to tuples

The sample code is as follows :

list1 = ['Google', 'Taobao', 'Runoob', 'Baidu']
tuple1 = tuple(list1)

The operation results are as follows :

Correlation function :
37- function list(): Used to convert tuples or strings into lists

63- function type(): Returns the type of the object

function type() There are two kinds of grammar :

type(object)
type(name, bases, dict)

The first syntax returns the type of the object , The second syntax returns a new type object .
The first grammar is commonly used , The second grammar is rarely used , So the following example code is only for the first syntax :

type1 = type(1)
type2 = type([1, 2, 'swh'])
type3 = type({
0: 'zero'})
x = 1
bool1 = type(x) == int # Judge whether the type is int type 

The operation results are as follows :

From the above running results, we can see that , function type() The returned string is not a string , It is type object ,type The object belongs to “Special Variables”.
And connect , You can also use relational operators “==” Judge the type .

64- function vars(): Returns the __dic__ attribute

The sample code is as follows :

class Person:
name = "Bill"
age = 19
country = "USA"
x1 = dir(Person) # Returns all properties of the class 
x2 = vars(Person) # Returns the __dic__ attribute 

The operation results are as follows :




It is said in the data that the object is returned __dic__ attribute , But I actually can't return , as follows :

class Person:
name = "Bill"
age = 19
country = "USA"
object1 = Person()
x1 = vars(object1)

The operation results are as follows :

Maybe the objects in the data also regard the class as an object ~ In my mind , The instantiation of a class is called an object .

65- function zip(): Packaging multiple iteratible objects

zip() Function to take iteratable objects as parameters , Package the corresponding elements in the object into tuples , And then return the objects made up of these tuples , The advantage is that it saves a lot of memory .

We can use list() Convert to output list .

If the number of elements in each iterator is inconsistent , Returns a list of the same length as the shortest object , utilize * The operator , Tuples can be unzipped into lists .
The sample code is as follows :

a = [1, 2, 3]
b = [4, 5, 6]
c = [11, 12, 13, 14, 15]
zip1 = zip(a, b)
list1 = list(zip1)
zip2 = zip(a, c)
list2 = list(zip2)

The operation results are as follows :

utilize * The operator , Tuples can be unzipped into lists , The sample code is as follows :

tup1 = ((1, 4), (2, 5), (3, 6))
a1, b1 = zip(*tup1)

The operation results are as follows :

66- function __import__(): The import module 、 Script 、 Classes and functions, etc

Although the key words import Can achieve the same function , But usually we use keywords at the beginning of the program import Enter the import operation , If we want to be in the middle of the program , You can use built-in functions __import__(), This will make the program look good .
The syntax is as follows :

__import__(name[, globals[, locals[, fromlist[, level]]]])

The meaning of optional parameters will not be explored for the time being .

The sample code is as follows :
my_script.py The code in is as follows :

print('Successfully imported my_ script!')
print('my_script execution completed!')

001-32- Built in functions .py The code in is as follows :

list1 = [1, 2, 3]
__import__('my_script')
list2 = [7, 8, 9]

The operation results are as follows :


Reference material :https://blog.csdn.net/wenhao_ir/article/details/125100220


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved