current position:Home>Understand Python's built-in function and add a print function yourself

Understand Python's built-in function and add a print function yourself

2022-01-29 16:00:35 Coriander Chat Game

Little knowledge , Great challenge ! This article is participating in “     A programmer must have a little knowledge  

This article also participates in  「 Digging force Star Program 」    , Win a creative gift bag , Challenge creation incentive fund

Write python All of my classmates should have used it print function , We don't define why we can call this function ?

The answer is because print It's a built-in function ,python The built-in functions of are commonly used tool functions , It is also a built-in function of the system , Let's talk about the built-in function today , Take a look at , I don't say much nonsense , Start

1、 What are built-in functions ?

python Built in functions refer to python Self contained function , This function does not need to be defined , And different built-in functions have different functions , You can use it directly .

#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
import builtins
def test():
    print("dsada")
if __name__ == '__main__':
    #    Add built-in function 
    builtins.__dict__["testFunc"] = test
    testFunc()
    pass
 Copy code 

2、 What are the built-in functions ?

Official documentation Links :docs.python.org/3.9/library…

Here I take a screenshot of the function , You can make an overview , You can guess what these functions do by looking at their names

image-20211010222503993.png

Group the above functions :

Mathematics :sum(),pow(),sum(),round()

Random classes :choice(),random(),seed(),shuffle(),uniform()

Digital class :abs(),min(),max(),divmod(),ascii()

System class :xxxattr,xxxmethod,

data type :set(),map(),tuple(),list(),bool(),int(),str(),

comprehensive : Others fall into this category

3、 Special function description

3.1 exec

Format :exec obj

obj The object can be a string ( Such as a single sentence 、 Sentence block ), File object , Or it can have been compile Precompiled code objects .

for instance

    exec( "print(' Coriander ')")
 Copy code 

3.2 eval

Format :eval( obj[, globals=globals(), locals=locals()] )

obj It can be a string object or has been created by compile Compiled code objects .globals and locals It's optional , Represents objects in the global and local namespaces, respectively , among globals It has to be a dictionary , and locals Is an arbitrary mapping object .

x = 3
print(eval('3*x'))
​
 Copy code 

The output is 9 ,eval You can reference context

3.3 compile

Format :compile( str, file, type )

compile The sentence is from type type ( Include ’eval’: coordination eval Use ,’single’: With a single statement exec Use ,’exec’: With multiple statements exec Use ) Lieutenant general str The statements inside are created as code objects .file It's where the code is stored , Usually it is ”.

compile The purpose of statement is to provide one-time bytecode compilation , There is no need to recompile in each subsequent call .

compile() Function will string Compile as code object , The compiled code object is then exec Statement execution , And then you can use eval() Function evaluates it .filename The parameter should be the file name from which the code reads . If the file name is generated internally ,filename The parameter value should be the corresponding identifier .kind Parameter assignment string The category of the code contained in the parameter

3.4 globals and locals

globals() All global variables in the current location will be returned as dictionary type .

locals() Returns all local variables of the current location in dictionary type .

For the function , Method , lambda Function , class , And realized call Class instance of a method , It is returned True.

4、 Add a built-in function

During the development process, some functions often call , But it's troublesome to guide the bag every time , Just think about whether you can add some tool functions to the built-in functions , As long as there's a problem , Others will have the same problem , In fact, the solution is very simple , Is in the builtins in dict Just add a function to , Here is an example :

#!/usr/bin/env python
# encoding: utf-8""" #Author:  Coriander  @time: 2021/10/10 0010  Afternoon  10:22 """
import builtins
def test():
    print("dsada")
if __name__ == '__main__':
    #    Add built-in function 
    builtins.__dict__["testFunc"] = test
    testFunc()
    pass Copy code 

5、 summary

python There is nothing special about the built-in functions of , It's just some tools and methods provided by the system , The implementation is also very simple , Remember these common tools and methods , In development, we can get twice the result with half the effort ,

copyright notice
author[Coriander Chat Game],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201291600342994.html

Random recommended