扫码阅读
手机扫码阅读

Python导包,花里胡哨

21 2024-09-27

我们非常重视原创文章,为尊重知识产权并避免潜在的版权问题,我们在此提供文章的摘要供您初步了解。如果您想要查阅更为详尽的内容,访问作者的公众号页面获取完整文章。

查看原文:Python导包,花里胡哨
文章来源:
啥都会一点的研究生
扫码关注公众号
Python Import Tricks Summary

Python Import Tricks Summary

This summary outlines key Python import tricks.

1) __import__

While the common syntax for importing modules is import numpy as np, an alternative approach is to use __import__ as np = __import__('numpy'), achieving the same result.

2) __all__

In a scenario where a.py imports all functions from b.py using from b import *, the introduction of __all__ in b.py can restrict the imports to only those specified in the __all__ list, for example __all__ = ['test1', 'test2'] will only import test1 and test2.

3) Absolute Imports

Absolute imports are used to import a specific module using its full path. For example, to import the hello function from say_hello.py located within nested directories, one would use from demo1.demo2.demo3.say_hello import hello in example.py.

4) if __name__ == '__main__'

The statement if __name__ == '__main__' is used to execute code only when the script is run directly, not when it is imported by another script. For instance, in a.py, the print statement within this conditional will only execute when a.py is run, not when a.py is imported elsewhere.

5) sys.path and Importing

The sys.path list contains the directories that Python searches in when importing modules. You can append your own paths to sys.path to allow Python to search additional directories for modules to import, for example, sys.path.append('/apple/orange/pear').

6) Relative Imports

Relative imports are used to import modules from the same directory or parent directories without specifying the full path. For example, from .c import hello_from_c in b.py is a relative import that imports hello_from_c from c.py, which is in the same directory.

That concludes this session's content. See you next time!

想要了解更多内容?

查看原文:Python导包,花里胡哨
文章来源:
啥都会一点的研究生
扫码关注公众号