Python built-in functions

Source: Internet
Author: User
Tags iterable list of attributes

Python built-in functions

Dir (_ builtins __)

1. 'abs '. Obtain the absolute value of the input parameter.

abs(x, /)    Return the absolute value of the argument.
1 >>> abs(10)2 103 >>> abs(-10)4 10

2. 'all' is used to determine whether all elements in the given iterable parameter are not 0, '', False, or iterable empty. If yes, True is returned. Otherwise, False is returned.

all(iterable, /)    Return True if bool(x) is True for all values x in the iterable.        If the iterable is empty, return True.
1 >>> all([1, 2])2 True3 >>> all([1, 0])4 False5 >>> all([])6 True

3. 'any' is used to determine whether all the specified iterable parameters are empty objects. If they are empty, 0, or false, False is returned, if not all values are null, 0, or false, True is returned.

any(iterable, /)    Return True if bool(x) is True for any x in the iterable.        If the iterable is empty, return False.
1 >>> any([1, 2])2 True3 >>> any([1, 0])4 True5 >>> any([])6 False

4. 'ascii ': The _ repr _ method of the input parameter is automatically executed (the object is converted to a string)

ascii(obj, /)    Return an ASCII-only representation of an object.        As repr(), return a string containing a printable representation of an    object, but escape the non-ASCII characters in the string returned by    repr() using \\x, \\u or \\U escapes. This generates a string similar    to that returned by repr() in Python 2.
1 >>> ascii (10) 2 '10' 3 >>> ascii ('abc') 4 "'abc'" 5 >>> ascii ('your mom Hi ') 6 "'\ u4f60 \ u5988 \ u55e8 '"

5. 'bin', returns the binary representation of an integer int or long integer long int.

bin(number, /)    Return the binary representation of an integer.
1 >>> bin(1024)2 '0b10000000000'

6. The 'bool 'function is used to convert a given parameter to a boolean type. If no parameter exists, False is returned.

7. 'bytearray', returns a new byte array. The elements in this array are variable, and the value range of each element is 0 <= x <256.

8. 'bytes ', String Conversion into word throttling. The first input parameter is the string to be converted, and the second parameter is converted to the byte eg. bytes (s, encoding = 'utf-8'), bytes (s, encoding = 'gbk') occupies 8 bytes; in UTF-8 encoding format, A Chinese Character occupies three bytes. in gbk encoding format, a Chinese character occupies two bytes.

9. 'callable' is used to check whether an object is callable. If True is returned, the object may still fail to be called. If False is returned, the object called ojbect will never succeed. For functions, methods, lambda functions, classes, and class instances that implement the _ call _ method, True is returned.

callable(obj, /)    Return whether the object is callable (i.e., some kind of function).        Note that classes are callable, as are instances of classes with a    __call__() method.
1 >>> callable(int)2 True3 >>> class Test():4 ...     def __call__(self):5 ...         return 16 ... 7 >>> test = Test()8 >>> test()9 1

10. 'chr', numeric to character

chr(i, /)    Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
1 l = []2 for i in range(0x10ffff + 1):3     try:4         print(i, chr(i), end=" ")5     except:6         l.append(i)7 8 print(l)9 print(len(l))

11. For 'classmethod', the modifier's function does not need to be instantiated and the self parameter is not required. However, the first parameter must be the cls parameter representing its own class and can be used to call class attributes, class methods, instantiated objects, etc.

12. 'compile ', receives the. py file or string as an input parameter, and compiles it into a python bytecode

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)    Compile source into a code object that can be executed by exec() or eval().        The source code may represent a Python module, statement or expression.    The filename will be used for run-time error messages.    The mode must be 'exec' to compile a module, 'single' to compile a    single (interactive) statement, or 'eval' to compile an expression.    The flags argument, if present, controls which future statements influence    the compilation of the code.    The dont_inherit argument, if true, stops the compilation inheriting    the effects of any future statements in effect in the code calling    compile; if absent or false these statements do influence the compilation,    in addition to any features explicitly specified.
>>> str = "for i in range(0,10): print(i)" >>> c = compile(str,'','exec')>>> c<code object <module> at 0x00000000022EBC00, file "", line 1>>>> exec(c)0123456789>>> str = "3 * 4 + 5">>> a = compile(str, '', 'eval')>>> a<code object <module> at 0x00000000022EB5D0, file "", line 1>>>> eval(a)17

13. The 'compute' function is used to create a complex number of values for real + imag * j, or to convert a string or number to a complex number. If the first parameter is a string, you do not need to specify the second parameter.

14. 'copyright ',


15. 'credit ',


16. 'delattr' is used to delete attributes.

delattr(obj, name, /)    Deletes the named attribute from the given object.        delattr(x, 'y') is equivalent to ``del x.y''
>>> class Test():...     def __init__(self):...         self.name  = 'w'...         self.age = 20... >>> test = Test()>>> test.name'w'>>> test.age20>>> delattr(test, 'name')>>> test.nameTraceback (most recent call last):  File "<console>", line 1, in <module>AttributeError: 'Test' object has no attribute 'name'>>> del test.age>>> test.ageTraceback (most recent call last):  File "<console>", line 1, in <module>AttributeError: 'Test' object has no attribute 'age'

17. 'dict 'is used to create a dictionary.

18. If 'dir' is not included, a list of variables, methods, and definitions in the current range is returned. If a parameter is included, a list of attributes and methods of the parameter is returned. If the parameter contains method _ dir _ (), the method is called. If the parameter does not contain _ dir _ (), this method collects parameter information to the maximum extent.

dir(...)    dir([object]) -> list of strings        If called without an argument, return the names in the current scope.    Else, return an alphabetized list of names comprising (some of) the attributes    of the given object, and of attributes reachable from it.    If the object supplies a method named __dir__, it will be used; otherwise    the default dir() logic is used and returns:      for a module object: the module's attributes.      for a class object:  its attributes, and recursively the attributes        of its bases.      for any other object: its attributes, its class's attributes, and        recursively the attributes of its class's base classes.
1 >>> dir()2 ['__builtins__', '__doc__', '__name__']3 >>> dir(list)4 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

19. 'divmod' combines the divisor and remainder calculation results to return a tuple (a/B, a % B) that contains the quotient and remainder ).

1 divmod(x, y, /)2     Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.
1 >>> divmod(10, 3)2 (3, 1)

20. Reload the module.

reload(module, exclude=['sys', 'os.path', 'builtins', '__main__'])    Recursively reload all modules used in the given module.  Optionally    takes a list of modules to exclude from reloading.  The default exclude    list contains sys, __main__, and __builtin__, to prevent, e.g., resetting    display, exception, and io hooks.

21. 'enumerate' is used to combine a data object that can be traversed (such as a list, tuples, or strings) into an index sequence and list both data and data subscript, it is generally used in a for loop.

22. 'eval' is used to execute a string expression and return the value of the expression.

eval(source, globals=None, locals=None, /)    Evaluate the given source in the context of globals and locals.        The source may be a string representing a Python expression    or a code object as returned by compile().    The globals must be a dictionary and locals can be any mapping,    defaulting to the current globals and locals.    If only globals is given, locals defaults to it.
1 >>> x = 102 >>> eval('3 * x')3 30

23. 'exec ': run the python code (it can be compiled or not compiled) without returning the result (None)

1 exec(source, globals=None, locals=None, /)2     Execute the given source in the context of globals and locals.3     4     The source may be a string representing one or more Python statements5     or a code object as returned by compile().6     The globals must be a dictionary and locals can be any mapping,7     defaulting to the current globals and locals.8     If only globals is given, locals defaults to it.
1 >>> exec(compile("print(123)","<string>","exec"))2 1233 >>> exec("print(123)")4 123

24. 'filter' is used to filter the sequence, filter out non-conforming elements, and return a new list composed of Conforming Elements. This receives two parameters. The first parameter is a function, and the second parameter is a sequence. Each element of the sequence is passed as a parameter to the function for determination. Then, True or False is returned, finally, add the elements that return True to the new list.

25. 'float' is used to convert integers and strings into floating point numbers.

26. 'format', # string formatting

format(value, format_spec='', /)    Return value.__format__(format_spec)        format_spec defaults to the empty string
1 >>> "{1} {0} {1 }". format ("hello", "world") 2 'World hello world' 3 >>> "website name: {name}, address {url }". format (name = "tutorial", url = "www.nimahai.com") 4'website name: tutorial, address: www.nimahai.com'

27. 'frozenset', return a frozen set. After the set is frozen, no more elements can be added or deleted.

28. 'getattr 'is used to return an object property value.

getattr(...)    getattr(object, name[, default]) -> value        Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.    When a default argument is given, it is returned when the attribute doesn't    exist; without it, an exception is raised in that case.
>>> class Test():...     def __init__(self):...         self.name = 'w'... >>> test = Test()>>> getattr(test, 'name')'w'>>> test.name'w'>>> getattr(test, 'age')Traceback (most recent call last):  File "<console>", line 1, in <module>AttributeError: 'Test' object has no attribute 'age'>>> test.ageTraceback (most recent call last):  File "<console>", line 1, in <module>AttributeError: 'Test' object has no attribute 'age'>>> getattr(test, 'age', 20)20>>> test.ageTraceback (most recent call last):  File "<console>", line 1, in <module>AttributeError: 'Test' object has no attribute 'age'

29. 'globals' returns a dictionary, which includes key-value pairs consisting of all global variables and their values.

globals()    Return the dictionary containing the current scope's global variables.        NOTE: Updates to this dictionary *will* affect name lookups in the current    global scope and vice-versa.
a =100print(globals()){'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000000001E867F0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '1.py', '__cached__': None, 'a': 100}

'Hasattr ',
'Hash', takes the hash value of the input parameter and returns
'Help': receives an object as a parameter and returns all attributes and methods of the object in more detail.
'Hex': receives a decimal number and converts it to hexadecimal format.
'Id', returns the memory address. It can be used to check whether two variables point to the same memory address.
'Input', prompting the user to input and return the content entered by the user (whatever the input is, it is converted to the string type)
'Int', converted to an integer
'Isinstance' to determine whether the object is an instance of a class. e.g. isinstance ([, 3], list)
'Isbuckets' to check whether this class is a derived class of another class. If yes, True is returned; otherwise, False is returned.
'Iter ',
'Len', returns the string length, measured in characters in python3 and in bytes in python2.
'License ',
'LIST', converted to list type
'Locals', returns a dictionary that includes all local variables and key-value pairs composed of their values.
'Map' is used as a real parameter to input the function to every element that can be iterated, and the results returned by each function call are added to the return value of map. E.g. tuple (map (lambda a: a + 1, (, 3) returns (, 4)
'Max': receives serialized data and returns the element with the largest value.
'Memoryview' to view the memory address
'Min', returns the element with the smallest value
'Next ',
'Object ',
'Oct': receives a decimal number and converts it to octal.
'Open ',
'Ord ', letters to numbers, view ASCII code table
'Power': returns the result of x ** y.
'Print ',
'Properties' to obtain all attributes of an object
'Range' to obtain random numbers from 0 to 10, or random characters such as. range (10 ).
'Repr': Execute the _ repr _ method in the input object.
'Failed': sorts serialized data in reverse order and returns a new object. Note the difference with the reverse method of the object. The latter is to change the object in place.
'Round ', returns the result after rounding.
'Set', to set type
'Setattr ',
'Slice 'returns a new object for serialized data slices. Eg. slice (start subscript, end subscript, step size), step size is 1 by default
'Sorted' returns a new object in a forward sorting of serialized data. Note the difference between the sort method and the object. The latter is to change the object in place.
'Staticmethod', returns the static method
'Str', which converts bytes to strings. The first input parameter is the byte to be converted, and the second parameter is based on the encoding to convert to a string.
'Sum ',
'Super', returns the base class
'Tuple', converted to the tuples
'Type', object type returned
'Vars': returns all variables in the current module.
'Zip' receives multiple serialized data types and classifies the elements in each serialized data into tuples Based on the index location.

 

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.