- Hands-On Penetration Testing with Python
- Furqan Khan
- 466字
- 2021-07-02 14:13:55
Modules and packages
Every Python script is called a module. Python has been designed with reusability and ease of code in mind. For this reason, every Python file we create becomes a Python module and is eligible to be invoked or used within any other file or script. You might have learned in Java how to import classes and reuse them with other classes. The idea is pretty much the same here, except that we are importing the whole file as a module and we can reuse any method, class, or variable of the imported file. Let's take a look at an example. We will create two files, child.py and parent.py, and put the following code in each, as follows:

Let's now try to explore Python packages and how they can be used. In Java, a package is nothing but a folder or directory that collects logically connected class files in Java. Packages do the same in Python; they collect logically connected Python modules. It is always recommended to use packages, as this keeps the code clean and makes it reusable and modular.
As mentioned earlier, a Python package is a normal directory. The only difference is that in order to make a normal directory behave like a Python package, we must place an empty __init__.py file inside the directory. This indicates to Python which directories it should use as packages. Let's go ahead and create a package called shapes. We will place an empty Python file called __init__.py and another file called area_finder.py inside it:

Let's now put the following code in the area_finder.py file. Let's also create another file called invoker.py and place it outside the shapes folder that we created. The code of the invoker is given on the right-hand side of the following image, while the code of the area_finder is given on the left-hand side:

The preceding code is a straightforward example of how to use packages in Python.We created a package called shapes and placed a file called area_finder in it, which will compute the area of a shape. Then, we went ahead and created a file called invoker.py outside the shapes folder, and imported the area_finder script from the package in multiple ways (for demonstration purposes). Finally, we used one of the aliases to invoke the find_area() method.
- Facebook Application Development with Graph API Cookbook
- 小程序?qū)崙?zhàn)視頻課:微信小程序開發(fā)全案精講
- Animate CC二維動畫設(shè)計與制作(微課版)
- 編寫高質(zhì)量代碼:改善C程序代碼的125個建議
- Quarkus實踐指南:構(gòu)建新一代的Kubernetes原生Java微服務(wù)
- 精通網(wǎng)絡(luò)視頻核心開發(fā)技術(shù)
- Hands-On Enterprise Automation with Python.
- 表哥的Access入門:以Excel視角快速學(xué)習(xí)數(shù)據(jù)庫開發(fā)(第2版)
- Multithreading in C# 5.0 Cookbook
- 現(xiàn)代C++編程實戰(zhàn):132個核心技巧示例(原書第2版)
- C++程序設(shè)計教程(第2版)
- Python Web自動化測試設(shè)計與實現(xiàn)
- 從零開始學(xué)UI:概念解析、實戰(zhàn)提高、突破規(guī)則
- RESTful Web API Design with Node.js
- Unreal Engine Game Development Cookbook