Python learning - object oriented (module)

1 module introduction In Python, all the methods and variables defined by you are stored in a file, which is used by so...
2.1 module import
2.2 __name__ attribute
2.3 dir() function
1 module introduction
  • In Python, all the methods and variables defined by you are stored in a file, which is used by some scripts or interactive interpreter instances. This file is called a module.
  • A module is a file that contains all the functions and variables you define. py is the suffix.
  • Modularity refers to decomposing a complete program into small modules, and building a complete program through module combination.
  • Advantages of Modularization: convenient development, maintenance and reuse
  • How to access module content:
    - to access the variables in the module, the syntax is: module name. Variable name
    - to access the function in the module, the syntax is: module name. Function name
    - to access the object in the module, the syntax is: module name. Object name
    Example 1:
import sys # import sys introduces the sys.py modular print('The command line parameters are as follows:') for i in sys.argv: # sys.argv Is a list of command line arguments. print(i) print('\n\nPython The path is',sys.path,'\n') # sys.path Contains a list of paths for the Python interpreter to automatically find the required modules.
2 module creation and use

2.1 module import

  • Mode of module import:
    – 1. Introduce the syntax of an external module into a module: import the module name, which is the py file.
    – 2. If the module name is long or complex, you can use import as…… Syntax: import module name as module alias
    – 3. We can also introduce some contents specified in the module. Syntax: from module name import variable, variable
    – 4. Alias for some content specified in the import module. The syntax is: from module name import variable as alias
    – 5. It is also feasible to import all the contents of a module into the current namespace (less recommended). Syntax: from module name import *, the effect is equivalent to: import module name

  • You can import the same module multiple times, but the instance of the module will only be created once, that is, no matter how many times you execute import, a module will only be imported once.

  • When the interpreter encounters the import statement, if the module is in the current search path, the module will be imported.

  • Because modules need to be imported before they can be called, module import statements, such as import statements, are generally placed at the front of the code.
    Example 2:
    First create the module in the path where the current file is located_ One module, the contents of which are as follows:

def print_func(name): print('hello,',name)
# Import module_one module import module_one # module_ Print of one module_ Func function module_one.print_func('Zhang San') # Output result: hello, Zhang San
  • When executing the import statement, the Python interpreter finds the corresponding module file according to the search path
    – the search path is a list of all directories that an interpreter will search first;
    – the search path is composed of a series of directory names from which the Python interpreter looks for the introduced modules;
    – the search path can be determined by defining environment variables;
    - the search path is determined when Python is compiled or installed, and the new library should be modified when installing;
    – the search path is stored in the path variable in the sys module. Enter the following code in the Python interactive interpreter IDLE:
import sys sys.path

The results are as follows:

['', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\Lib\\idlelib', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python36\\site-packages', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages']

sys.path The output is a list where the first entry is the empty string '' representing the current directory.

  • The result of executing in the interactive interpreter is the directory of the Python interpreter. For scripts, it is the directory of the running script.
  • Note: if there is a file with the same name as the module to be imported in the current directory, the module to be imported will be blocked, so do not store the file with the same name as the module in the current directory.

2.2 __name__ attribute

  • There is one inside a module__ name__ , through which we can get the name of the module.
  • If the py file runs directly, then__ name__ The default is equal to the string 'main'.
  • name__ Property value is__ Main indicates that the current module is the main module, and there is only one main module in a program.
    Example 3:
    Contents of Fibonacci sequence module:
# Fibonacci sequence module def fib(n): # Fibonacci sequence defined to n: 11 23 5 8 13 21 34 55 89 144 233377 610 987 a,b = 0,1 # Equivalent to a=0 b=1 while b < n: print(b,end=' ') a,b = b,a+b # Note that a and b are assigned separately, that is, a=b,b=a+b, and the value of a in the expression of b=a+b is the value before the expression of a=b is executed # You can use the statement print(a,b) to observe the change of a and b values print() def fib2(n): # Fibonacci series back to n result = [] a = 0 b = 1 while b < n: result.append(b) a,b = b,a+b return result

Import Fibonacci sequence module:

import fibonacci as fibo # Call FIB function and fib2 function of fibonacci module fibo.fib(100) # Results of implementation: 11 2 3 5 8 13 21 34 55 89 print(fibo.fib2(1000)) # Output result: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987] print(__name__) # Output results:__ main__ print(fibo.__name__) # Output: fibonacci # If you need to use a function often, you can assign it to a local name fib=fibo.fib fib(100) # Results of implementation: 11 2 3 5 8 13 21 34 55 89
  • When a module is first introduced by another program, its main program runs. If we want to introduce a module and a program block in the module does not execute, we can use the__ name__ Property to make the block execute only when the module itself is running.
if __name__ == '__main__': print('The program itself is running') else: print('From another module')

The running result is: the program itself is running

  • be careful:
    – 1. Each module has one__ name__ Property, when its value is' main ', it indicates that the module itself is running, otherwise it is introduced.
    – 2. Under name and main are double underscores.

2.3 dir() function

  • The built-in function dir() finds all the names defined within the module and returns them as a list of strings.
    Example 4:
import module_one,fibonacci,sys lst1=dir(module_one) print(lst1) # ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'print_func'] lst2=dir(fibonacci) print(lst2) # ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'fib', 'fib2'] lst3=dir(sys) print(lst3)

Contents of lst3 list:

['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_getframe', '_git', '_home', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'set_asyncgen_hooks', 'set_coroutine_wrapper', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions', 'winver']
  • If no parameter is given, the dir() function lists all the names currently defined.
a=[1,2,3] lst4=dir() print(lst4)

result:

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'fibonacci', 'lst1', 'lst2', 'lst3', 'module_one', 'sys']

21 June 2020, 06:13 | Views: 5157

Add new comment

For adding a comment, please log in
or create account

0 comments