Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use import Module in python

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how python uses the import module. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Import module

Import declarations are often used in Python to use objects defined in other modules (that is, other .py files).

1) use _ _ name__

When we write Python library modules, we tend to run some test statements. When this program is import as a library, we do not need to run these test statements. One solution is to comment out the test statements in the module before import. A more elegant solution to Python is to use _ _ name__.

The following is a simple library program TestLib.py. When running TestLib.py directly, _ _ name__ is "_ _ main__". If import, _ _ name__ is "TestLib".

Def lib_func (a): return a + 10def lib_func_another (b): return b + 20if _ _ name__ ='_ _ main__': test = 101 print (lib_func (test))

We import the TestLib above in user.py.

Import TestLibprint (TestLib.lib_func)

You can try not to use if _ _ name__=='__main__', in TestLib.py and compare the results.

2) more ways to use import

Import TestLib as test # references the TestLib module and renames it t

For example:

Import TestLib as tprint (t.lib_func)

From TestLib import lib_func # refers only to lib_func objects in TestLib and skips the TestLib reference field

This has the advantage of reducing the memory footprint of the referenced module.

For example:

From TestLib import lib_funcprint (lib_func)

From TestLib import * # references all objects in TestLib and skips the TestLib reference field

For example:

From TestLib import * print (lib_func (120)) Thank you for your reading! This is the end of the article on "how to use the import module in python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report