Python's string reflection mechanism

Distinguish the two concepts, f1, "f1", the former is a function name, and the latter is a string, which are different things.. We can use f(1) to call a function "f(1)" cannot call .It is not possible to call functions that look the same. You cannot use strings to call functions that look the same.

A simple WEB router is implemented here

Perform different functions according to different URLs

But to write hundreds of functions, is that too much to write?

Nor is it

This is the result

The reflection mechanism was proposed in this case.

Take a look at the simplest function

That is, str is consistent with the function called below

Then we can think of it this way, can we just call the function by letting us enter the string

It must be possible, the needs are out, and you will be satisfied

See next operation

Python has such a function built-in

This function has two parameters

The front is a module or method, and the back is a string

The general principle is like this

This function lets the get function let the program find a member called inp in the commons module

This is a dynamic process


This is python's reflection, a string-based drive mode. But it still hasn't been done very well, which is a commonplace question/what if the str passed in by the user cannot be matched?

This is the improved code

Through the hasattr function, it is used to determine whether there is a corresponding string in the function.


So this example is to guide each other in the same directory, what if it is global?

The code is refactored to look like this

Analyze what you wrote

First of all, we can see that we did not define any line of import statement

The format of inp is defined as the form of commons/home, which simulates the URL address in the web framework

You can see the error once

Look at this line of code

The user's input is processed, so that we will get two strings and save them in the modules and func variables respectively

Then let the program import the module with the same name as the string saved in the modules variable

The subsequent procedure is the same as before.

Recommended Posts

Python's string reflection mechanism