Python Programming by Example (2015)

10. Building Own Python Module

This chapter explains how to build own Python module.

10.1 Creating Simple Module

In this section, we create a simple module. We will call functions from external file (*.py) in the same package, main package.

Firstly, create a file, simplemodule.py, and write these scripts.

def perform(a, b):

    return a * 2.5 + b

def calculate(a,b):

    return a + b * 5

You also can create a class on Python file, for instance simpleadvmodule.py and write these scripts.

from math import *

class City:

    # class data

    city_count = 0

    city_id = 0

    # constructor

    def __init__(self, name='', x=0, y=0):

        self.name = name

        self.x = x

        self.y = y

        City.city_count += 1  # access all City classes

        self.city_id = City.city_count

    def __str__(self):

        return 'City: ' + self.name + ',id=' + str(self.city_id) + ',x=' + str(self.x) + ',y=' + str(self.y)

    # class attributes

    def move_to(self, x=0, y=0):

        self.x += x

        self.y += y

    def distance(self, other_city):

        xi = pow(other_city.x - self.x, 2)

        yi = pow(other_city.y - self.y, 2)

        return sqrt(xi + yi)

    def __del__(self):

        # get class name

        class_name = self.__class__.__name__

        print('class ', class_name, ' destroyed')

Now you access functions from simplemodule.py and simpleadvmodule.py files using import statement.

Write these scripts.

# access our modules

import simplemodule

import simpleadvmodule

# use simplemodule

num1 = simplemodule.perform(10, 5)

print(num1)

num1 = simplemodule.calculate(4, 3)

print(num1)

# use simpleadvmodule

city_a = simpleadvmodule.City('Hamburg', 8, 12)

city_b = simpleadvmodule.City('Berlin', 5, 7)

print(city_a)

print(city_b)

city_a.move_to(4, 3)

city_b.move_to(7, 12)

print(city_a)

print(city_b)

Save into a file, called ch10_01.py. Run the program.

$ python3 ch10_01.py

Program output:

p10-1

10.2 Building Own Python Package

In previous program, we create a module in Python package. We create a package and then use it in our program. 

You can create a package, called Learning, by creating folder. Inside Learning folder, you create folders: Algebra and Arithmetic.

The following is our package structure.

p10-3

Now we add several files in each folder

·        Learning folder: __init__.py, common.py, Computer.py and foo.py

·        Learning/Algebra folder: __init__.py and add.py

·        Learning/Arithmetic folder: __init__.py and calculate.py

The following is script implementation for each file.

common.py

def do_something():

    print('call do_something()')

Computer.py

class Computer:

    # constructor

    def __init__(self, name=''):

        self.name = name

    def __str__(self):

        return 'Computer: ' + self.name

    def say_hello(self):

        print("I'm computer, called", self.name)

foo.py

def foo():

    print('call foo()')

__init__.py from Learning folder.

from common import do_something

from Computer import Computer

from foo import foo

add.py

def add(a, b):

    return a + b

__init__.py from Learning/Algebra folder.

from Learning.Algebra.add import add

calculate.py

def calculate(a, b):

    return a + b * 2.8

__init__.py from Learning/Arithmetic folder.

from Learning.Arithmetic.calculate import calculate

Now we can access our package. Create a file, called ch10_02.py, and write these scripts.

import sys

sys.path.append('./Learning')

import Learning

Learning.foo()

Learning.do_something()

a = Learning.Computer('myPC')

a.say_hello()

import Learning.Algebra as algebra

b = algebra.add(10, 5)

print(b)

import Learning.Arithmetic as arith

c = arith.calculate(5, 8)

print(c)

Save and run the program.

$ python3 ch10_02.py

Program output:

p10-2