if __name__==‘__main__‘:用法:
When we run the module file at the command line , the Python interpreter places a special variable __name__ __main__ , and if the module is imported elsewhere hello , the if judgment will fail, so this if Testing allows a module to execute some extra code when it runs through the command line, most commonly by running tests.
if __name__==‘__main__‘: test()
Scope
In a module, we may define many functions and variables, but some functions and variables we want to use for others, some functions and variables we want to use only within the module. In Python, this is done by a _ prefix.
Normal functions and variable names are public and can be referenced directly, such as: abc , x123 , PI etc.;
__xxx__Such variables are special variables, can be directly referenced, but there are special purposes, such as the above __author__ , __name__ is a special variable, hello the module definition of the document can also be accessed with special variables __doc__ , our own variables are generally not used this variable name;
similar _xxx and __xxx such functions or variables are non-public (private), should not be directly referenced, such as _abc , __abc etc.;
The reason why we say that private functions and variables should not be directly referenced, rather than "cannot" be directly referenced, is because Python does not have a way to completely restrict access to private functions or variables, but from a programming habit should not refer to private functions or variables.
Private functions or variables should not be referenced by others, what is the use of them? Take a look at the example:
def _private_1(name): return ‘Hello, %s‘ % namedef _private_2(name): return ‘Hi, %s‘ % namedef greeting(name): if len(name) > 3: return _private_1(name) else: return _private_2(name)
We expose the function in the module and greeting() hide the internal logic with the private function, so that the calling greeting() function does not care about the internal private function details, which is also a very useful way to encapsulate and abstract the code, namely:
Functions that do not need to be referenced externally are all defined as private, and only functions that need to be referenced externally are defined as public.
V. Use of modules in Python