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 .
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 .
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 :
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 :
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 .
The sample code is as follows :
x1 = bin(10)
print(x1)
The operation results are as follows :
About functions bool(), See my other blog post https://blog.csdn.net/wenhao_ir/article/details/125439660
This function is 3.7 Only after version , The frequency of use is not high , Don't introduce too much for the time being .
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.
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 :
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 .
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 :
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 :
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 :
function dict() For details, please refer to the blog https://blog.csdn.net/wenhao_ir/article/details/125412774 Of “01- attach 2”
function dir() For details, please refer to the blog https://blog.csdn.net/wenhao_ir/article/details/125421060
The sample code is as follows :
result_1 = divmod(5, 2)
The operation results are as follows :
About functions enumerate() Detailed introduction , See my other blog post :https://blog.csdn.net/wenhao_ir/article/details/125443427
For more information, see the function compile() Introduction to , Specifically, it is the... In this blog post 11 individual .
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
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
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 .
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 :
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
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 :
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 :
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 .
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 :
The sample code is as follows :
hex1 = hex(10)
The operation results are as follows :
Be careful : function hex() It returns a string object .
The sample code is as follows :
str1 = 'CSDN'
id1 = id(str1)
The operation results are as follows :
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 .
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 .
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 :
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 :
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 :
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 .
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
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 :
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 :
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 :
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 .
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 .
function next() Introducing 35- function iter() I have already introduced , I won't go into it here .
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 :
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 :
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 :
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 ).
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 :
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 :
function print() See my other blog post for a detailed introduction to :https://blog.csdn.net/wenhao_ir/article/details/125390532
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 .
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 :
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 .
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 :
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 :
function set() In Bowen https://blog.csdn.net/wenhao_ir/article/details/125424671 Has been introduced in , I won't repeat it here .
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 :
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]
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 .
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 .
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 :
A detailed introduction to this function , You can see another blog post of mine :https://blog.csdn.net/wenhao_ir/article/details/125472478
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
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 .
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 .
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 :
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