Functions, Classes, Modules & Packages

User-Define Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

Python provides many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.

# function definition
def a_function(arg, default_arg=0):
    pass

# invoking the function
a_function(1)
a_function(1, 2)
a_function(1, default_arg=2)

User-Defined Classes

Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state (ref.)

class User:
    """Store user information"""

    # Class variable
    name = "name=User"

    # Class constructor
    def __init__(self, a_name):
        # Instance public variable
        self.name = f"name={a_name}"
        # Instance protected variable
        self._name = f"_name={a_name}"
        # Instance private variable
        self.__name = f"__name={a_name}"

    # Instance public method
    def get_name(self):
        """get user name"""
        return self.__name

# Create an instance of the User class
user = User('User1')

# prints the user name
print(User.name)
print(user.name)
print(user._name)
print(user.get_name())
#print(user.__name)  # <- this is will generate: AttributeError: 'User' object has no attribute '__name'

Modules

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable _name (ref.).

Packages

Packages are a way of structuring Python’s module namespace by using dotted module names (ref.)

Module = Python file
e.g. hello module:
    hello.py

Package = Directory containing “__init__.py” file and one or more Python modules
e.g.: hello package:
    hello/__init__.py
    hello/hello.py

Example importing a module or function from a Python package

Current directory:

calculate.py
calculator_package

calculator_package directory:

__init__.py
calculator_module.py

File: calculator_module.py

class Calculator: pass

File: calculate.py

#
# importing from a package a module
from calculator_package import calculator_module
calculator = calculator_module.Calculator()
print(calculator.sum(1, 2))

#
# importing from a package's module a class
from calculator_package.calculator_module import Calculator
calculator = Calculator()

#
# importing from a package's module a class as a different class name (alias)
from calculator_package.calculator_module import Calculator as MyCalculator
calculator = MyCalculator()