Python - Common built-in variables

Directly on the code

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
This is a comment __doc__ print this part
"""

# Dictionary-way return of all the built-in variables 
Print (VARS ())

# Returns the current path of the file 
Print ( __FILE__ )

# Get inlet path of the file, the current output file will return None 
Print ( __PACKAGE__ )

# The most important __name__ acquisition path plus the file name of the import file 
Print ( __name__ )

Results of the

{ ' The __name__ ' : ' __main__ ' , ' __doc__ ' : ' \ n-this is a comment which will be printed __doc__ part \ n- ' , ' __PACKAGE__ ' : None, ' __loader__ ' : <Object _frozen_importlib_external.SourceFileLoader AT 0x000001F7A6E6C438>, ' __spec__ ' : None, ' __annotations__ ' : {}, ' the __builtins__ ' : <Module1 ' the builtins ' (built- in )>,'__file__' : ' F.: / SQ_Python_Easy / D10_ Object Oriented / embedded variables 1.py ' , ' __cached__ ' :} None
F.: / SQ_Python_Easy / D10_ Object Oriented / embedded variable 1.py
None
__main__

 

A knowledge point: vars ()

Python built-in functions, you can return all the current module built-in variables

 

Knowledge point two: __ file__ acquisition path

Where Module: os

Variable effect: points to the current file

The full path of the current file:  the os.path.realpath ( __FILE__ ) 

The current file Contents:  os.path.dirname (the os.path.realpath ( __FILE__ )) 

Parent directory of the current file belongs directory:  os.path.dirname (os.path.dirname (the os.path.realpath ( __FILE__ ))) 

 

Knowledge Point three: __ package__

"""
Built-in variables 1.py
"""

#!/usr/bin/env python
# -*- coding: utf-8 -*-

Print ( __PACKAGE__ ) # Output None
"""
Built-in variables 2.py
"""

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from the Test Import built-in variables 1.py

# Directory output file import; will output test

 

Knowledge Point four: __ name __ (focus)

Python system variables

Scene One:  IF the __name__ == ' __main__ ' : 

The most common scenario: When you run the current file,  __name__  output is  __main__  , so you can add  if  judged to execute a particular code

 

Scene Two: import other files

 Built-in variables 1.py  file

#!/usr/bin/env python
# -*- coding: utf-8 -*-

print(__name__)
if __name__ == '__main__':
    print("main")

Run  the built-in variable 1.py  file

__main__ 
hand

 

 Built-in variables 2.py  file

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from the Test Import built-in variables 1.py

Run  the built-in variable 2.py  file

Object oriented D10_ built variable 1

 

It can be seen when you run the built-in variable 2.py file, import it as a built-in variable 1.py, the value of the output __name__ is built 1.py path variable in the project directory

Guess you like

Origin www.cnblogs.com/poloyy/p/12507104.html