Python module--Special variables

Source: Internet
Author: User

is the global variable that the system automatically builds for this module when the module is imported.

What you need to know:

    • __doc__ its contents as a comment at the beginning of the py file. Print (__doc__) to see
    • __cached__ The location where the bytecode of the py file is stored. In the "Pycharmprojects" project directory can see _ "_pycache__" folder, which is stored in the import Py file compiled into bytecode.
    • The package where the __package__ py file resides. As shown in the example

Commonly used for:

    • __file__ The relative path where the current execution file resides (as opposed to the directory location where the current file is executed)

Example 1:

The s1.py content is print (__file__), where the file storage path is: c:/users/sea/pycharmprojects/untitled1/s1.py

Execute Python s1.py after switching to the directory where s1.py is located in cmd c:/users/sea/pycharmprojects/untitled1

Output is s1.py instead of c:/users/sea/pycharmprojects/untitled1/s1.py

Application:

Import OS Import syssys.path.append (Os.path.dirname (Os.path.dirname (Os.path.abspath(__file__)))

Adds the upper-level directory of the current file to the search path. At this point, no matter how the copy can be successfully imported module, because the path can be changed dynamically with the copy.

    • __name__ Special variable __name__ = = "__main__" only when executing the current file

Application:

def run ():     Print ('run') # run () executes only if the file to be executed is the current file. When this module is imported into other modules, run ()if__name__"__main__"is not executed:      Run ()

Python module--Special variables

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.