Python built-in functions--summary

Source: Internet
Author: User
Tags abs access properties object object ord pow vars

    • Math Operations (7)
    • Type conversions (24)
    • Sequence Operations (8)
    • Object Operations (7)
    • Reflection Operation (8)
    • Variable operation (2)
    • Interactive Operations (2)
    • File Operations (1)
    • Compilation Execution (4)
    • Decorators (3)
 Mathematical Operations ABS: Absolute value >>> ABS ( -2) 2divmod: Returns the quotient and remainder of two values >>> Divmod (5,2) (2, 1) >> Divmod (5.5,2) (2.0, 1.5 Max: Returns the maximum value of an element in an iterative object or the maximum value of all parameters copy code >>> max (three-in-one) # Pass in 3 parameters take 3 3>>> max (' 1234 ') # to pass in an iterator object, Take its maximum element value ' 4 ' >>> max ( -1,0) # value defaults to the larger 0>>> max ( -1,0,key = ABS) # passed in the absolute value function, Then the parameter will be absolute and then the larger-1 copy code min: Returns the minimum value of an element in an iterative object or the minimum value of all parameters copy code >>> min (three-in-one) # Pass in 3 parameters take 3 smaller 1>>> min ( ' 1234 ') # Pass in an iterative object, take its minimum element value ' 1 ' >>> min ( -1,-2) # value defaults to the lesser value -2>>> min ( -1,-2,key = ABS) # passed in the absolute value function, the parameters will be To get the absolute value and then take the smaller-1 copy Code POW: Returns the power of two numeric values or their modulo value with a specified integer >>> pow (2,3) >>> 2**3>>> pow (2,3,5) >> > Pow (2,3)%5round: Rounding evaluation of floating-point numbers >>> round (1.1314926,1) 1.1>>> round (1.1314926,5) 1.13149sum: Sum of each element in an iterative object with an element type of numeric value copy code # incoming Iteration Object >>> sum ((1,2,3,4)) 10# element type must be numeric >>> sum (( 1.5,2.5,3.5,4.5) 12.0>>> sum ((1,2,3,4),-10) 0 Copy code type conversion BOOL: Creates a new Boolean value based on the logical value of the parameter passed in >>> bool () # Parameter FALSE&GT;&G not passed int;> bool (0) #数值0, empty sequence equivalent is falsefalse>>> bool (1) Trueint: Creates a new integer >>> int () #不传入参数时 based on the parameters passed in, resulting in 0. 0>>> Int (3) 3>>> int (3.6) 3float: Creates a new floating-point number >>> float () #不提供参数的时候 based on the parameters passed in and returns 0.00.0>> > float (3) 3.0>>> float (' 3 ') 3.0complex: Creates a new complex number >>> complex () #当两个参数都不提供时 based on the parameters passed in, returning the complex 0j. 0j>>> complex (' 1+2j ') #传入字符串创建复数 (1+2j) >>> complex (#传入数值创建复数 (1+2j) str: Returns the string representation of an object (to the user) Copy Code >>> str () ' >>> str (none) ' None ' >>> str (' abc ') ' ABC ' >>> STR (123) ' 123 ' Copy Code ByteArray: Create a new byte array based on the parameters passed in >>> bytearray (' Chinese ', ' utf-8 ') ByteArray (b ' \xe4\xb8\xad\xe6\x96\x87 ') Bytes: Creates a new immutable byte array based on the parameters passed in >>> bytes (' Chinese ', ' utf-8 ') B ' \xe4\xb8\xad\xe6\x96\x87 ' Memoryview: Create a new Memory view object based on the parameters passed in >>> v = memoryview (b ' ABCEFG ') >>> v[1]98>>> v[-1] 103ord: Returns the integer corresponding to the Unicode character >>> Ord (' A ') 97CHR: Returns the Unicode character corresponding to the integer >>> chr #参数类型为整数 ' a ' Bin: Converting integers to 2 strings >>> bin (3) ' 0B11 ' Oct: converting integers to 8 numeric charactersString >>> Oct (+) ' 0o12 ' hex: convert integers to 16 strings >>> hex ' 0xf ' tuple: Create a new tuple >>> tuple () based on the parameters passed in Create empty tuple () >>> tuple (' 121 ') #传入可迭代对象 without passing in parameters. Create a new tuple with its elements (' 1 ', ' 2 ', ' 1 ') List: Create a new list based on the parameters passed in >>>list () # do not pass in parameters, create an empty list [] >>> list (' ABCD ') # to pass in an iterator object, Create a new list with its elements [' A ', ' B ', ' C ', ' d ']dict: Create a new dictionary copy code based on the parameters passed in >>> dict () # Returns an empty dictionary when no parameters are passed in. {}>>> dict (A = 1,b = 2) # You can create a dictionary by passing in a key-value pair. {' B ': 2, ' a ': 1}>>> dict ([' A ', ' B '],[1,2]) # You can pass in a mapping function to create a dictionary. {' B ': 2, ' a ': 1}>>> dict ((' A ', 1), (' B ', 2)) # You can pass in an iterative object creation dictionary. {' B ': 2, ' A ': 1} Copy Code set: Creates a new collection based on the parameters passed in >>>set () # does not pass in parameters, creates an empty collection set () >>> a = set (range (10)) # passes in an iterator object, Create Collections >>> a{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}frozenset: Creates a new immutable collection based on the parameters passed in >>> a = Frozenset (range) >>& Gt Afrozenset ({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) Enumerate: Create an enumeration object based on an iterative object >>> seasons = [' Spring ', ' Summer ', ' Fall ', ' Wint Er ']>>> list (enumerate (seasons)) [(0, ' Spring '), (1, ' Summer '), (2, ' FAll '), (3, ' Winter ')]>>> list (Enumerate (seasons, start=1)) #指定起始值 [(1, ' Spring '), (2, ' Summer '), (3, ' Fall '), (4, ' Winter ')]range: Creates a new Range object copy code based on the parameters passed in >>> a = range (Ten) >>> B = Range (1,10) >>> C = Range ( 1,10,3) >>> a,b,c # Output A,b,c (range (0, ten), Range (1, 1, 3)) >>> list (a), list (b), List (c) # Don't output a,b,c elements ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 4, 7]) >>> Copy code iter: Create a new iterative object based on the parameters passed in Copy code >>> a = iter (' ABCD ') #字符串序列 >>> A<str_iterator object at 0x03fb4fb0>>>> next (a) ' a ' & Gt;>> Next (a) ' B ' >>> next (a) ' C ' >>> next (a) ' d ' >>> next (a) Traceback (most recent call Last): File ' <pyshell#29> ', line 1, <module> next (a) stopiteration copy code slice: Creates a new Tile object copy code based on the parameters passed in &GT;&G t;> C1 = Slice (5) # definition c1>>> c1slice (none, 5, none) >>> C2 = Slice (2,5) # definition c2>>> c2slice (2, 5 , None) >>> C3 = Slice (1,10,3)# definition C3>>> c3slice (1, 10, 3) Copy Code Super: Creates a new subclass and parent-class relationship based on the parameters passed in the Proxy object Copy code # defines the parent class A>>> class A (object): Def __i Nit__ (self): print (' a.__init__ ') #定义子类B, inheriting a>>> class B (A): def __init__ (self): print (' b.__init__ ' ) Super (). __init__ () #super调用父类方法 >>> B = b () b.__init__a.__init__ Copy Code object: Create a new Object object >>> a = O Bject () >>> a.name = ' Kim ' # Cannot set property Traceback (most recent call last): File "<pyshell#9>", line 1, in <mo dule> a.name = ' Kim ' attributeerror: ' Object ' object has no attribute ' name ' sequence operation all: determine if each element of an iterative object is a true value copy code ;>> all ([up]) #列表中每个元素逻辑值均为True, returns truetrue>>> all ([0,1,2]) #列表中0的逻辑值为False, returns falsefalse>> > All (()) #空元组True >>> all ({}) #空字典True复制代码any: Determines whether an element that iterates over an object has an element that has a true value copy code >>> any ([0,1,2]) # The list element has a true, then returns truetrue>>> any ([0,0]) #列表元素全部为False, returns falsefalse>>> any ([]) #空列表False >> > any ({}) #空字典False复制代码filter: Filters The elements of an iterative object using the specified method copy code;>> A = List (range (1,10)) #定义序列 >>> a[1, 2, 3, 4, 5, 6, 7, 8, 9]>>> def if_odd (x): #定义奇数判断函数 ret Urn x%2==1>>> list (filter (if_odd,a)) #筛选序列中的奇数 [1, 3, 5, 7, 9] Copy code map: Use the specified method to function the elements of each of the iterated objects that are passed in, generating a new iterative object > >> a = map (ord, ' ABCD ') >>> A<map object at 0x03994e50>>>> list (a) [98, 100]next: Return to iteration The next element value in the object copy code >>> a = iter (' ABCD ') >>> next (a) ' A ' >>> next (a) ' B ' >>> next (a) ' C ' > >> Next (a) ' d ' >>> next (a) Traceback (most recent call last): File "<pyshell#18>", line 1, in <modul E> Next (a) stopiteration# when the default parameter is passed in, if the iterator object and the element is not returned, the element value is returned, and if all elements have returned, the default value specified is returned without throwing the stopiteration Exception >>> Next (A, ' e ') ' E ' >>> next (A, ' e ') ' E ' copy code reversed: Reverses the sequence to generate a new iterative object >>> A = reversed (range ( 10) # Incoming Range object >>> A # type becomes iterator <range_iterator object at 0x035634e8>>>> list (a) [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]sorted: Sorts the objects that can be iterated, returns a new list copy code >>> a = [' A ', ' B ', ' d ', ' C ', ' B ', ' A ']>>> a[' A ', ' B ', ' d ', ' C ', ' B ', ' A ']>>> sorted (a) # Default by character ASCII code [' A ', ' B ', ' A ', ' B ', ' C ', ' d ']>>> sorted (A,key = str.lower) # Convert to lowercase and then sort, ' a ' and ' a ' values like ' B ' and ' B ' values [' a ', ' a ', ' B ', ' B ', ' C ', ' d '] copy Code zip: Aggregates an element in the same position in each iterator passed in, returning a new tuple type iterator >>> x = [4,5,6,7,8] #长度3 >>> y = [x] #长度5 >>> list ( Zip (x, y) # takes the minimum length 3[(1, 4), (2, 5), (3, 6)] object operation Help: Returns the helper information for the object Copy Code >>> Assist (str) to the class str in module bui  Ltins:class Str (object) |  STR (object= ")-str |   STR (bytes_or_buffer[, encoding[, errors]), str |  | Create a new string object from the given object.  IF Encoding or |  Errors is specified and then the object must expose a data buffer | That'll be decoded using the given encoding and error handler.  |  Otherwise, returns the result of object.__str__ () (If defined) | or Repr (object).  | encoding defaults to sys.getdefaultencoding ().  | Errors defaults to ' strict '.   |  |   Methods defined here: | |  __add__ (self, value,/) | Return Self+value.    | Copy Code dir: Returns an object or a list of properties in the current scope copy Code >>> import math>>> math<module ' math ' (built-in) >>>> dir (math) [' __doc__ ', ' __loader__ ', ' __name__ ', ' __package__ ', ' __spec__ ', ' ACOs ', ' Acosh ', ' ASIN ', ' Asinh ', ' atan ', ' atan2 ', ' Atanh ', ' ceil ', ' copysign ', ' cos ', ' cosh ', ' degrees ', ' e ', ' Erf ', ' erfc ', ' exp ', ' EXPM1 ' ', ' fabs ', ' factorial ', ' floor ', ' fmod ', ' frexp ', ' fsum ', ' gamma ', ' gcd ', ' hypot ', ' inf ', ' isclose ', ' isfinite ', ' Isinf ',  ' isNaN ', ' ldexp ', ' lgamma ', ' Log ', ' log10 ', ' log1p ', ' log2 ', ' modf ', ' nan ', ' pi ', ' pow ', ' radians ', ' sin ', ' sinh ', ' sqrt ', ' Tan ', ' tanh ', ' trunc ') copy code ID: Returns the unique identifier of the object >>> a = ' Some text ' >>> ID (a) 69228568hash: Gets the hash value of the object >> > Hash (' Good Good study ') 1032709256type: Returns the type of the object, or creates a new type copy code based on the parameters passed in >>> type (1) # Returns the type of the object <class ' int ' > #使用type函数创建类型D with attributes infod>>> D = Type (' d ', (A, B), Dict (infod= ' some thing defined in D ')) >>>D = d () >>> d.infod ' Some thing defined in D ' copy code len: Returns the length of the object copy code >>> len (' ABCD ') # string >>> len (byt Es (' abcd ', ' Utf-8 ')) # byte array >>> len (1,2,3,4) # tuple >>> len ([1,2,3,4]) # list >>> len (range (1,5)) # Range Object >>> len ({' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4}) # dictionary >>> Len ({' A ', ' B ', ' C ', ' d '}) # collection >>> Len ( Frozenset (' ABCD ')) #不可变集合复制代码ascii: Returns the printable table string representation of an object copy code >>> ASCII (1) ' 1 ' >>> ASCII (' & ') ' & ' >>> ASCII (9000000) ' 9000000 ' >>> ASCII (' Chinese ') #非ascii字符 "' \\u4e2d\\u6587 '" Copy Code format: formatted display value copy code # The string can provide the parameter ' s ' none>>> format (' Some string ', ' s ') ' some string ' >>> format (' some string ') ' Some string ' # Shaping values can provide parameters that have ' B ' C ' ' d ' o ' x ' x ' n ' none>>> format (3, ' B ') #转换成二进制 ' one ' >>> format (' C ') #转换unicode成 Characters ' a ' >>> format (one, ' d ') #转换成10进制 ' one ' >>> format (' o ') #转换成8进制 ' + ' >>> format (one, ' X ') # Convert to 16 lowercase to indicate ' B ' >>> format (one, ' X ') #转换成16进制 uppercase letters ' B ' >>> format (one, ' n ') #和d一样 ' one ' >>> format (one) #默认和d一样 ' one ' #浮点数可以提供的参数有 ' e ' e ' ' F ' f ' n ' G ' none>& gt;> format (314159267, ' e ') #科学计数法, default reserved 6-bit fractional ' 3.141593e+08 ' >>> format (314159267, ' 0.2e ') #科学计数法, specifying 2 decimal places reserved 3.14e+08 ' >>> format (314159267, ' 0.2E ') #科学计数法, specifies to retain 2 decimal places, with uppercase E for ' 3.14E+08 ' >>> format (314159267, ' F ' ) #小数点计数法, the default reserved 6 decimal places ' 314159267.000000 ' >>> format (3.14159267000, ' f ') #小数点计数法, by default 6 decimal places ' 3.141593 ' >>> Format (3.14159267000, ' 0.8f ') #小数点计数法, specifies to retain 8 decimal places ' 3.14159267 ' >>> format (3.14159267000, ' 0.10f ') #小数点计数法, Specifies that the reserved 10-bit fractional ' 3.1415926700 ' >>> format (3.14e+1000000, ' F ') #小数点计数法, Infinity converted to the size of the letter ' INF ' #g的格式化比较特殊, assuming p is the reserved scale specified in the format , first try to format the scientific notation, get the power exponent exp, if -4<=exp<p, then use decimal notation, and retain p-1-exp decimal place, otherwise counted by the fractional count method, and press P-1 to retain the decimal places >>> format ( 0.00003141566, '. 1g ') #p =1,exp=-5 = = " -4<=exp<p not established, counted by scientific notation, reserved 0 decimal places ' 3e-05 ' >>> format (0.00003141566, ' .2g ') #p =1,exp=-5 = = " -4<=exp<p not established, counted by scientific notation, reserved 1 decimal places ' 3.1e-05 ' >>> format (0.00003141566, '. 3g ') #p =1,exp=-5 = = " -4<=exp<p not established, counted by scientific notation, reserved 2 decimal places ' 3.14e-05 ' >>> format (0.00003141566, '. 3G ') #p =1,exp=-5 = = " -4<=exp<p not established, counting by scientific notation, reserved 0 decimal places, e use uppercase ' 3.14E-05 ' >>> format (3.1415926777, '. 1g ') #p =1,exp= 0 = = " -4<=exp<p set up, counting by fractional notation, reserved 0 decimal places ' 3 ' >>> format (3.1415926777, '. 2g ') #p =1,exp=0 = =" -4<=exp<p established, Count by fractional count, reserved 1 decimal places ' 3.1 ' >>> format (3.1415926777, '. 3g ') #p =1,exp=0 = = " -4<=exp<p established, counted by fractional count, reserved 2 decimal places ' 3.14 ' >>> format (0.00003141566, '. 1n ') #和g相同 ' 3e-05 ' >>> format (0.00003141566, '. 3n ') #和g相同 ' 3.14e-05 ' >>> format (0.00003141566) #和g相同 ' 3.141566e-05 ' copy code vars: Returns a dictionary of local variables and their values in the current scope, or returns an object's property list copy code # Acting on class instances > >> class A (object): Pass>>> a.__dict__{}>>> VARs (a) {}>>> a.name = ' Kim ' >>> A. __dict__{' name ': ' Kim '}>>> vars (a) {' name ': ' Kim '} Copy Code reflection action __import__: Dynamic Import Module index = __import__ (' index ') Index.sayhello () Isinstance: Determines whether an object is a class or an instance of any of the class elements in a type tuple >>> isinstance (1,int) TruE>>> isinstance (1,STR) false>>> isinstance (1, (INT,STR)) Trueissubclass: Determines whether a class is another class or subclass of any class element in a type tuple copy code >>> issubclass (bool,int) true>>> Issubclass (bool, STR) false>>> Issubclass (bool, (str,int)) True copy code hasattr: Checks if an object contains property copy code # Definition class A>>> classes Student:def __init__ (self,name): Self.name = name >>> s = Student (' Aim ') >>> hasattr (S, ' name ') #a含有name    Property True>>> hasattr (S, ' age ') #a不含有age属性False复制代码getattr: Gets the property value of the object copy code # defines the class Student>>> classes Student: def __init__ (self,name): Self.name = name>>> getattr (s, ' name ') #存在属性name ' Aim ' >>> getattr (S, ' age ', 6) #不存在属性age, but provided default value, return default value >>> getattr (S, ' age ') #不存在属性age, default value not provided, call error Traceback (most recent called last): File "& Lt;pyshell#17> ", line 1, in <module> getattr (S, ' age ') Attributeerror: ' Stduent ' object have no attribute ' age ' copy Code setattr: Setting property values for an object copy code >>> class Student:def __init__ (self,name): Self.name = Name >>> a = Student (' Kim ') >>> a.name ' Kim ' >>> setattr (A, ' name ', ' Bob ') >>> A.nam E ' Bob ' copy code delattr: Delete The property of the object copy code # define classes a>>> class A:def __init__ (self,name): self.name = name Def Sayhell  O (self): print (' Hello ', self.name) #测试属性和方法 >>> a.name ' wheat ' >>> a.sayhello () Hello Wheat # Delete Properties >>> Delattr (A, ' name ') >>> A.nametraceback (most recent): File "<pyshell#47>", line 1, in <module&    Gt A.nameattributeerror: ' A ' object has no attribute ' name ' Copy code callable: detects if object can be called copy code >>> class B: #定义类B def __ca        Ll__ (self): print (' instances is callable now. ') >>> callable (b) #类B是可调用对象True >>> B = B () #调用类B >>> callable (b) #实例b是可调用对象True >>> B () #调用实例b成功instances is callable now. Copy code variable action globals: Returns a dictionary of global variables and their values in the current scope >>> globals () {' __spec__ ': None, ' __ package__ ': None, ' __builtins__ ': <module ' builtins ' (built-in);, ' __name__': ' __main__ ', ' __doc__ ': None, ' __loader__ ': <class ' _frozen_importlib. Builtinimporter ' >}>>> a = 1>>> globals () #多了一个a {' __spec__ ': None, ' __package__ ': none, ' __builtins __ ': <module ' builtins ' (built-in), ' a ': 1, ' __name__ ': ' __main__ ', ' __doc__ ': None, ' __loader__ ': <class ' _froz En_importlib.  Builtinimporter ' >}locals: Returns a dictionary of local variables and their values in the current scope copy code >>> def f (): print (' before define a ') print (locals ()) #作用域内无变量 A = 1 print (' after define a ') print (locals ()) #作用域内有一个a变量 with a value of 1 >>> f<function f at 0x03d4  0588>>>> f () before define a {} After define a{' a ': 1} Copy Code interaction Print: Printing output to standard output objects >>> print (1) 2 3>>> print (1,2,3,sep = ' + ') 1+2+3>>> print (1,2,3,sep = ' + ', end = ' =? ') 1+2+3=?input: Read user input value >>> s = input (' Please input your name: ') "Please input your name:ain>>> s ' Ain ' file operation Open: Opens the file with the specified pattern and encoding, returns the file read/write Object # T for the text read and write, b for binary read/write >>> a = open (' test.txt ', ' RT ') >>>A.read () ' Some text ' >>> a.close () compile execution compile: Compile the string into code or an AST object so that it can be executed through an EXEC statement or eval-evaluated to copy code >>> # The process statement uses exec>>> Code1 = ' For I in Range (0,10): print (i) ' >>> compile1 = compile (Code1, ', ' exec ') >>& Gt EXEC (compile1) 0123456789>>> #简单求值表达式用eval >>> code2 = ' 1 + 2 + 3 + 4 ' >>> compile2 = compile (COD E2, ', ' eval ') >>> eval (compile2) 10 copy Code eval: Perform dynamic expression evaluation >>> eval (' 1+2+3+4 ') 10exec: Execute Dynamic statement block >> > exec (' a=1+2 ') #执行语句 >>> a3repr: Returns the string representation of an object (to the interpreter) >>> a = ' some text ' >>> str (a) ' some Text ' >>> repr (a) "' Some text '" Decorator property: The adorner copy code that marks the attribute >>> class C:def __init__ (self): self        . _name = "@property def name (self):" "" "" "" "" "" Return Self._name @name. Setter def name (self,value): If value is none:raise runtimeerror (' name CA N not being None ') Else:self._name = value &GT;&Gt;> C = C () >>> C.name # Access Properties ' >>> c.name = None # Verify when setting properties Traceback (most recent call last): File " <pyshell#84>, line 1, in <module> c.name = None File ' <pyshell#81> ', line one, in name raise Runt Imeerror (' name can not being None ') Runtimeerror:name can not be none>>> c.name = ' Kim ' # setting properties >>> C.name #  Access Properties ' Kim ' >>> del c.name # Delete attribute, not provided deleter cannot delete Traceback (most recent call last): File "<pyshell#87>", line 1, in <module> del c.nameattributeerror:can ' t delete attribute>>> c.name ' Kim ' copy Code classmethod: Label method for class method Adorner copy code >>> class C: @classmethod def f (cls,arg1): print (CLS) print (ARG1) >>> C.F (' class object called class method ') <class ' __main__. The C ' > class object calls the class method >>> C = C () >>> c.f (' class instance object called Class method ') <class ' __main__. C ' > class instance object calling class method copy code Staticmethod: an adorner that marks the method as a static method copy code # Use adorners to define static methods >>> class Student (object): Def __init__ ( Self,name): Self.name = NamE @staticmethod def sayHello (lang): print (lang) if lang = = ' en ': print (' welcome! ') Else:print (' Hello! ') >>> student.sayhello (' en ') #类调用, ' en ' passed to the lang parameter enwelcome!>>> B = Student (' Kim ') >>> B.sayhello (' zh ') #类实例对象调用, ' zh ' passed to lang parameter en hello

  

Python built-in functions--summary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.