Movatterモバイル変換


[0]ホーム

URL:


Modules and packages

Module is a Python source code file, i.e. a file with .py extension.

Package is a directory which contains__init__.py file and can contain python modules and other packages.

Why to organize your code into modules and packages

  • Maintainability
  • Reusability
  • Namespacing
  • People unfamiliar with your project can get a clear overview just by looking at the directory structure of your project
  • Searching for certain functionality or class is easy

How to use

Let's use the following directory structure as an example:

food_store/    __init__.py    product/        __init__.py        fruit/            __init__.py            apple.py            banana.py        drink/            __init__.py            juice.py            milk.py            beer.py    cashier/        __ini__.py        receipt.py        calculator.py

Let's consider that banana.py file contains:

defget_available_brands():return["chiquita"]classBanana:def__init__(self,brand="chiquita"):ifbrandnotinget_available_brands():raiseValueError(f"Unknown brand:{brand}")self._brand=brand

Importing

Let's say that we need accessBanana class from banana.py file inside receipt.py. We can achive this by importing at the beginning of receipt.py:

fromfood_store.product.fruit.bananaimportBanana# then it's used like thismy_banana=Banana()

If we need to access multiple classes or functions from banana.py file:

fromfood_store.product.fruitimportbanana# then it's used like thisbrands=banana.get_available_brands()my_banana=banana.Banana()

A comprehensive introduction to modules and packages can be foundhere.


[8]ページ先頭

©2009-2025 Movatter.jp