This is the 16th day of my participation in the August Text Challenge.More challenges in August

πŸ“– preface

Marquez wrote in One Hundred Years of Solitude:

“The past is false, memory is a road of no return. No spring before it can be restored, and even the wildest and most persevering love is, in the final analysis, but a fleeting reality, eternal solitude.”

Today we talk about how to use Python’s built-in functions! Do not like spray, if there are suggestions welcome to supplement, discussion!

You can watch this blogger’s article about installation and LocalizationVsCode download, Installation and LocalizationAs well asPython series: windows10 configuration Python3.0 development environment!After installation, restart VsCode!

This article mainly introduces the functions of some built-in functions and their usage, as well as the main usage of some important functions in detail. For example, format(), zip(), Max (), and min().


On! Usage of built-in functions

When I first learned Python, I was always confused about the use and difference between built-in functions and built-in methods of some data types. Then I learned that both built-in functions and built-in methods were in Python builtins.py. The difference was that the built-in functions were directly defined in that file. These built-in methods are in different modules, so built-in functions are one level above the built-in methods of certain data types. Of course, both are functions. Therefore, its use method is as follows:

"@name: Sunny Chen @test: test font @msg: This is created by Sunny Chen @param: @return: Parameter2: finc1(parameter1, parameter2,....) All True (" sunny ") # built-in methods -- > the format for the data func2 (parameter1, parameter2,...). Name ="sunny" name.capitalize() print(name)Copy the code

So, when we use it, we just need to distinguish between a built-in function and a built-in method in a datatype class to know how to use it.


On! The functionality of built-in functions

The Python built-in function (official document can see simplified Chinese) : https://docs.python.org/zh-cn/3/library/functions.html?highlight=built#built-in-functions

You can see the advanced use of some important methods:

zipFunction — Zipper

"@name: Sunny Chen @test: test font @msg: This is created by Sunny Chen @param: @return: Names =["xiaochen","xiaojia","xiaowu"] ages=[21,22,30] print(zip(names,ages)) # return an iterator Print (list(zip(names,ages)) <zip object at 0x0000023C45B11FC8> # [('xiaochen', 21), ('xiaojia', 22), ('xiaowu', 30)]Copy the code

sortedFunction — sort

"@name: Sunny Chen @test: test font @msg: This is created by Sunny Chen @param: @return: If you want to sort the dictionaries in a sequence, Info =[{"name":"sunny Chen ","age":21,"sex":"man"}, {"name":"xiaojiajia","age":22,"sex":"man"}, {" name ":" xiaoxiaxia ", "age" : 23, "sex" : "woman"}] print (sorted (info, key = lambda x: x (" age "), reverse = True)) # # output is in reverse chronological order: [{" name ":  'xiaoxiaxia', 'age': 23, 'sex': 'woman'}, {'name': 'xiaojiajia', 'age': 22, 'sex': 'man'}, {'name': 'sunny chen', 'age': 21, 'sex': 'man'}]Copy the code

Max function advanced usage, how to get the oldest dictionary

"@name: Sunny Chen @test: test font @msg: This is created by Sunny Chen @param: @return: Print (Max (ages)) print(Max (ages)) print(Max (ages)) Print (Max (ages.values())) print(list(zip(ages.values(),ages.keys()))))) print(list(zip(ages.values(),ages.keys()))))) [(33, 'little jia jia), (21,' sunny Chen), (22, 'xiaoxiaxia)] print (Max (zip (which) values (), which the keys ()))) # results as follows: # small jiajia # 33 # [(33, 'little jia jia), (21,' sunny Chen), (22, 'xiaoxiaxia)] # (33,' little jia jia)Copy the code

__import__function

"@name: Sunny Chen @test: test font @msg: This is created by Sunny Chen @param: @return: Import_test print(import_test) # import_test.dogs() # __import__(" STR ") module_name ="import_test" m=__import__(module_name) #m = import_test print(m) m.dos ()Copy the code

Python__import()__ 与 importThe difference between!


On! What’s the difference?

inMaking the cloneSome of thepythonCode, found some projects are not directly used"Import"But through"__import () __.Function to import the module.

  1. importImport is a standard module, and the concept of a standard module is a folder that must contain__init__.pyFile. It acts more like a statement, andimportAfter the module comes in, in case the original module has any changes, can passreload()Reload.

  2. __import__()As a function, it can only take string arguments, and the return value can be used to operate directly. This function is usually used for dynamic loading, the most common scenario is plug-in support.

  • | import | import |

— – | — – | — – | | — – | tendency stationary statement | | dynamic loading for scene has clearly know which modules in project | module can run dynamic insertion, dynamic introduction for | | import OS # import inherent OS module Import (’employee’).find(name=’ employee’) # import(’employee’).find(name=’ employee’

When importing Python modules using import, the __import__() function is called by default. It is rare to use this function directly, and is generally used for dynamically loading modules. __import__(name, globals, locals, fromlist, level) Only name is mandatory. Other parameters are optional. Generally, name is used. Fromlist specifies the name of the submodule to be imported, and level specifies the import method (relative import or absolute import, both are supported by default). When the module name is package.module and the fromList argument is empty, the function returns the top-level module, the package module. If fromList =[module], return module.

So, the following statement returns the same result:

spam = __import__('spam', globals(), locals(), [], -1)
spam = __import__('spam.ham', globals(), locals(), [], -1)
Copy the code

And the following is specifiedfromlist, you can get the submodule.

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
eggs = _temp.eggs
saus = _temp.sausage
Copy the code

It can also be used if you want to import modules directly by nameimportlibThe moduleimport_moduleFunction. You can use__import__Function to implement delayed import of modules:

class LazyImport:
    def __init__(self, module_name):
        self.module_name = module_name
        self.module = None
 
    def __getattr__(self, name):
        if self.module is None:
            self.module = __import__(self.module_name)
        return getattr(self.module, name)
 
string = LazyImport("string")
print string.lowercase
Copy the code

For details, see —-Python’s built-in function __import()__ :Docs.python.org/zh-cn/3/lib…


πŸŽ‰ finally

  • For more references, see here:Chen Yongjia’s blog

  • Like the small partner of the blogger can add a concern, a thumbs-up oh, continue to update hey hey!