5. python modules and python modules
If _ name __= = '_ main _': Usage:
When we run the module file in the command line, the Python interpreter puts a special variable__name__
Set__main__
If you importhello
Module,if
The Judgment will fail. Thereforeif
The test allows a module to execute some additional code when running through the command line. The most common is to run the test.
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, and some functions and variables we want to use only within the module. In Python_
Prefix.
Normal Functions and variable names are public and can be directly referenced, for example:abc
,x123
,PI
And so on;
Similar__xxx__
Such variables are special variables that can be directly referenced, but have special purposes, such__author__
,__name__
Is a special variable,hello
The module-defined document annotations can also use special variables.__doc__
Access, we generally do not use this variable name for our own variables;
Similar_xxx
And__xxx
Such functions or variables are private and should not be directly referenced, such_abc
,__abc
And so on;
The reason we say that private functions and variables should not be directly referenced, rather than being directly referenced, is because Python does not have a way to completely restrict access to private functions or variables, however, in programming habits, private functions or variables should not be referenced.
Private functions or variables should not be referenced by others. What are their functions? See the example below:
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 make public in the modulegreeting()
Function, and the internal logic is hidden using the private function.greeting()
Functions do not need to care about the details of internal private functions. This is also a very useful method for code encapsulation and abstraction, namely:
All functions that do not need to be referenced externally are defined as private. Only functions that need to be referenced externally are defined as public.