After learning Python for almost a year, I suddenly realized that the built-in functions can greatly speed up the development efficiency. I spent a week sorting out 68 built-in functions and taking a look at how the built-in functions operate.

Due to the platform, the picture is not very clear. If you want to get the hd photo or PDF, you can go to my warehouse on Github or scan a photo to get it. There is a public reply: 003

Github address: github.com/hellgoddess…

Let’s start with the simple ones and once again recommend python’s various built-in functions to you. They are really easy to use, and it is really nice to use them without having to write them by hand.

Mathematical operations

  • Abs: sum over absolute values
>>> abs(-2)
2
Copy the code
  • Divmod: Returns the quotient and remainder of two numeric values
>>> divmod(9.4)
(2.1)
>>> divmod(3.3.2)
(1.0.1.2999999999999998)
Copy the code
  • Max: Returns the maximum value of an element or all parameters in an iterable
>>> max(1.2.3)
3
>>> max('123456')
'6'
>>> max(-1.0)
0
>>> max(-1.0,key=abs) If the absolute value function is passed in, all parameters are summed and maximized
-1
Copy the code
  • Min: Returns the minimum value of an element or all parameters in an iterable

Example Max, just come here

  • Pow: Returns the power of two numeric values or their modulo with the specified integer
>>> pow(2.3)
8
>>> 2**3
8
>>> pow(2.3.5)
3
>>> pow(2.3) %5
3
Copy the code
  • Round: Evaluates floating point numbers by rounding
>>> round(1.3149.1)
1.3
>>> round(1.13952456.3)
1.14
Copy the code
  • Sum: Sums each element in an iterable whose element type is numeric
>>> sum((1.2.3.4))
10
Copy the code

Type conversions: In type conversions, I’ll introduce a few that we commonly use

  • Tuple: Creates a new tuple based on the parameters passed in
>>> tuple(a)Create an empty tuple without passing an argument(a)>>> tuple('121') Pass in the iterable. Use its elements to create a new tuple
('1'.'2'.'1')
Copy the code
  • List: Creates a new list based on the parameters passed in
>>>list(a)Create an empty list without passing an argument
[] 
>>> list('abcd') Pass in the iterable and use its elements to create a new list
['a'.'b'.'c'.'d']
Copy the code
  • Dict: Creates a new dictionary based on the parameters passed in
>>> dict(a)Return an empty dictionary if no arguments are passed.
{}
>>> dict(a = 1,b = 2) You can create a dictionary by passing in key-value pairs.
{'b': 2.'a': 1}
>>> dict(zip(['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 iterable to create a dictionary.
{'b': 2.'a': 1}
Copy the code
  • Set: Creates a new collection based on the parameters passed in
>>>set(a)Create an empty collection without passing an argument
set(a)>>> a = set(range(10)) Pass in the iterable and create the collection
>>> a
{0.1.2.3.4.5.6.7.8.9}
Copy the code
  • Frozenset: Creates a new immutable set based on the parameters passed in
>>> a = frozenset(range(10))
>>> a
frozenset({0.1.2.3.4.5.6.7.8.9})
Copy the code
  • Enumerate: Creates enumerations based on iterable objects
>>> seasons = ['Spring'.'Summer'.'Fall'.'Winter']
>>> list(enumerate(seasons))
[(0.'Spring'), (1.'Summer'), (2.'Fall'), (3.'Winter')]
>>> list(enumerate(seasons, start=1)) # specify the starting value
[(1.'Spring'), (2.'Summer'), (3.'Fall'), (4.'Winter')]
Copy the code
  • Range: Creates a new range object based on the parameters passed in
>>> a = range(10)
>>> b = range(1.10)
>>> c = range(1.10.3)
>>> a,b,c Print a,b,c respectively
(range(0.10), range(1.10), range(1.10.3))
>>> list(a),list(b),list(c) Print the elements of a,b, and c separately
([0.1.2.3.4.5.6.7.8.9], [1.2.3.4.5.6.7.8.9], [1.4.7])

Copy the code
  • Iter: Creates a new iterable based on the parameters passed in
>>> a = iter('abcd') # string sequence
>>> a
<str_iterator object at 0x03FB4FB0>
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#29>", line 1.in <module>
    next(a)
StopIteration
Copy the code
  • Super: Creates a new proxy object (inherited, often polymorphic) based on the parameters passed in.

Sequence of operations

  • All: Determines whether each element of an iterable is True
>>> all([1.2]) Return True for each element in the list
True
>>> all([0.1.2]) # 0 in the list has a logical value of False, return False
False
>>> all(()) # empty tuple
True
>>> all({}) # empty dictionary
True
Copy the code
  • Any: Determines whether elements of the iterable have rue value elements
>>> any([0.1.2]) Return True if one of the list elements is True
True
>>> any([0.0]) If all list elements are False, return False
False
>>> any([]) # an empty list
False
>>> any({}) # empty dictionary
False
Copy the code
  • Filter: Filters the elements of an iterable using the specified method
>>> a = list(range(1.10)) # define sequence
>>> a
[1.2.3.4.5.6.7.8.9]
>>> def if_odd(x) : # define odd number judge function
    return x%2= =1

>>> list(filter(if_odd,a)) Filter the odd number in the sequence
[1.3.5.7.9]
Copy the code
  • Map: Generates a new iterable using the specified method area on the elements of each passed iterable
>>> a = map(ord.'abcd')
>>> a
<map object at 0x03994E50>
>>> list(a)
[97.98.99.100]
Copy the code
  • Next: Returns the value of the next element in the iterable
>>> 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 <module>
    next(a)
StopIteration

If the iterable does not return any more elements, the iterable returns its element values in turn. If all elements are returned, the iterable returns the default values specified by default without raising StopIteration
>>> next(a,'e')
'e'
>>> next(a,'e')
'e'
Copy the code
  • A reversed sequence generates a new iterable
>>> a = reversed(range(10)) Pass in the range object
>>> a Type becomes iterator
<range_iterator object at 0x035634E8>
>>> list(a)
[9.8.7.6.5.4.3.2.1.0]
Copy the code
  • Sorted: Sorts iterable objects and returns a new list
>>> a = ['a'.'b'.'d'.'c'.'B'.'A']
>>> a
['a'.'b'.'d'.'c'.'B'.'A']

>>> sorted(a) Sort by ASCII characters by default
['A'.'B'.'a'.'b'.'c'.'d']

>>> sorted(a,key = str.lower) 'a' has the same value as 'a' and 'b' has the same value as 'b'
['a'.'A'.'b'.'B'.'c'.'d']
Copy the code
  • Zip: Aggregates elements at the same position in each passed iterator, returning a new tuple type iterator
>>> x = [1.2.3] Length of # 3
>>> y = [4.5.6.7.8] Length of the # 5
>>> list(zip(x,y)) Take the minimum length 3
[(1.4), (2.5), (3.6)]
Copy the code

Object manipulation (rarely used, explanations can be found in mind maps)

Reflex action

  • _import_: Dynamically imports modules
index = __import__('index')
index.sayHello()
Copy the code
  • Isinstance: Determines whether an object is an instance of any class element in a non-class or type tuple
>>> isinstance(1.int)
True
>>> isinstance(1.str)
False
>>> isinstance(1, (int.str))
True
Copy the code
  • Issubclass: Determines whether a class is a subclass of any class element in another class or type tuple
>>> issubclass(bool.int)
True
>>> issubclass(bool.str)
False

>>> issubclass(bool, (str.int))
True
Copy the code
  • Hasatr: Checks whether an object has attributes
Define class A
>>> class Student:
    def __init__(self,name) :
        self.name = name

        
>>> s = Student('Aim')
>>> hasattr(s,'name') #a contains the name attribute
True
>>> hasattr(s,'age') #a does not contain age
False
Copy the code
  • Getattr: Gets the property value of an object
# class Student
>>> class Student:
    def __init__(self,name) :
        self.name = name

>>> getattr(s,'name') # attribute name exists
'Aim'

>>> getattr(s,'age'.6) The age attribute does not exist, but a default value is provided. The default value is returned

>>> getattr(s,'age') The age attribute is not present. No default value is provided
Traceback (most recent call last):
  File "<pyshell#17>", line 1.in <module>
    getattr(s,'age')
AttributeError: 'Stduent' object has no attribute 'age'
Copy the code
  • Seattr: Sets the property value of an object
>>> class Student:
    def __init__(self,name) :
        self.name = name

        
>>> a = Student('Kim')
>>> a.name
'Kim'
>>> setattr(a,'name'.'Bob')
>>> a.name
'Bob'
Copy the code
  • Delattr: Deletes an attribute of an object
Define class A
>>> class A:
    def __init__(self,name) :
        self.name = name
    def sayHello(self) :
        print('hello',self.name)

# Test properties and methods
>>> a.name
'wheat'
>>> Hello wheat a.s ayHello ()# delete attribute
>>> delattr(a,'name')
>>> a.name
Traceback (most recent call last):
  File "<pyshell#47>", line 1.in <module>
    a.name
AttributeError: 'A' object has no attribute 'name'
Copy the code
  • Callable: Checks whether an object can be called
>>> class B: Define class B
    def __call__(self) :
        print('instances are callable now.')

        
>>> callable(B) Class B is callable
True
>>> b = B() Call class B
>>> callable(b) Instance B is a callable
True
>>> b() Calling instance B succeeded
instances are callable now.
Copy the code

Variable operating

  • Globals: Returns a dictionary of global variables and their values in the current scope
>>> globals()
{'__name__': '__main__'.'__doc__': None.'__package__': None.'__loader__': <class '_frozen_importlib.BuiltinImporter'>,'__spec__': None.'__annotations__': {}, '__builtins__': <module 'builtins' (built-in) >,'a': [1.2.3.4.5.6.7.8.9].'if_odd': <function if_odd at 0x03544F60>}
Copy the code
  • Locals: Returns a dictionary of local variables and their values in the current scope
>>> def f() :
    print('before define a ')
    print(locals()) There are no variables in scope
    a = 1
    print('after define a')
    print(locals()) There is an A variable in scope with the value 1

    
>>> f
<function f at 0x03D40588>
>>> f()
before define a 
{} 
after define a
{'a': 1}
Copy the code

interactions

  • print
  • input

I can use both of these with my eyes closed

File operations

  • Open: opens the file using the specified mode and encoding and returns the file read/write object
# t for text read/write, b for binary read/write
>>> a = open('test.txt'.'rt')
>>> a.read()
'some text'
>>> a.close()
Copy the code

The following built-in functions for us to write procedures, will definitely be the finishing touch, a word cow!!

Compile implementation

  • Compile: Compile strings into code or AST objects that can be executed by exec statements or evaluated by eval
>>> # process statements use exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,' '.'exec')
>>> exec (compile1)
0
1
2
3
4
5
6
7
8
9


>>> Use eval for simple evaluation expressions
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,' '.'eval')
>>> eval(compile2)
10
Copy the code
  • Eval: Evaluates a valid expression in a string, returns the result, converts a string into an object (such as a list, tuple, dict, and string), and inverts a string back into an object using backquotes
>>> eval((2, 2 'pow)')# evaluate a valid expression in a string,
4
>>> eval('2 + 2')
4
>>> eval("n + 4")
85
Convert strings into corresponding objects (such as conversions between list, tuple, dict, and string)
>>> a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> b = eval(a)
>>> b
[[1.2], [3.4], [5.6], [7.8], [9.0]]
>>> a = "{1:'xx',2:'yy'}"
>>> c = eval(a)
>>> c
{1: 'xx'.2: 'yy'}
>>> a = "(1, 2, 3, 4)"
>>> d = eval(a)
>>> d
(1.2.3.4)

# invert the string converted using backquotes back to the object
>>> list1 = [1.2.3.4.5]
>>> `list1`
'[1, 2, 3, 4, 5]'
>>> type(`list1`)
<type 'str'>
>>> type(eval(`list1`))
<type 'list'>
>>> a = eval(`list1`)
>>> a
[1.2.3.4.5]

Copy the code
  • Exec: Executes dynamic statement blocks
>>> exec('a=1+2') # execute statement
>>> a
3
Copy the code
  • Repr: Returns a string representation of an object
>>> a = 'some text'
>>> str(a)
'some text'
>>> repr(a)
"'some text'"
Copy the code

A decorator

  • Property: Represents the decorator for the property
>>> class C:
    def __init__(self) :
        self._name = ' '
    @property
    def name(self) :
        """i'm the 'name' property."""
        return self._name
    @name.setter
    def name(self,value) :
        if value is None:
            raise RuntimeError('name can not be None')
        else:
            self._name = value

            
>>> c = C()

>>> c.name # access attributes
' '
>>> 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 11.in name
    raise RuntimeError('name can not be None')
RuntimeError: name can not be None

>>> c.name = 'Kim' # set attributes
>>> c.name # access attributes
'Kim'

>>> del c.name Deleter is not provided
Traceback (most recent call last):
  File "<pyshell#87>", line 1.in <module>
    del c.name
AttributeError: can't delete attribute
>>> c.name
'Kim'
Copy the code
  • Classmethod: decorator labeled as a classmethod
>>> class C:
    @classmethod
    def f(cls,arg1) :
        print(cls)
        print(arg1)

        
>>> C.f(Class object calls class method)
<class '__main__.C'> Class object calls class method >>>c = C() > > >c.f(Class instance object calls class method)
<class '__main__.C'> Class instance objects call class methodsCopy the code
  • Staticmethod: decorator marked as a staticmethod
Use decorators 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') # class call,'en' passed to the lang parameter
en
Welcome!

>>> b = Student('Kim')
>>> b.sayHello('zh')  # class instance object call,'zh' passed to the lang parameterUseful helloCopy the code

Go to the Github address

PythonGuide is a guide that covers the core knowledge that most python-related programmers need to know. Prepare for your Python interview with PythonGuide!