Working with Python Classes and External Modules

Defining and Using Classes

A class serves as a blueprint for creating objects that share common characteristics and behaviors. An object is a concrete instance produced from that blueprint.

Creating a Class

class SmartDevice:
    manufacturer = "Nova"
    shell_color = "graphite"

    def dial_number(self):
        print("Placing a call")

    def transmit_message(self):
        print("Sending a message")

The class keyword initiates the definition. By convention, class names begin with a capital letter to distinguish them from functions. Variables belonging to a class are called attributes, while functions defined inside a class are known as methods. The self argument represents the instance itself, and Python automatically passes the object reference in that position.

Instantiating and Inspecting an Object

class SmartDevice:
    manufacturer = "Nova"
    shell_color = "graphite"

    def dial_number(self):
        print("Placing a call")

    def transmit_message(self):
        print("Sending a message")

personal_device = SmartDevice()
print(personal_device)

The variable personal_device holds an object instantiated from the SmartDevice class.

Accessing Attributes and Invoking Methods

class SmartDevice:
    manufacturer = "Nova"
    shell_color = "graphite"

    def dial_number(self):
        print("Placing a call")

    def transmit_message(self):
        print("Sending a message")

personal_device = SmartDevice()
print(personal_device.manufacturer)   # Nova
personal_device.dial_number()         # Placing a call

Attributes are accessed through dot notaiton: object.attribute. Methods are called similarly but require parentheses: object.method().

class SmartDevice:
    manufacturer = "Nova"

    def dial_number(self, credit):
        print(f"Using {self.manufacturer} device with remaining balance: {credit}")

dev = SmartDevice()
dev.dial_number(250)   # Using Nova device with remaining balance: 250

The instance automatically substitutes for self, while the numeric argument maps to the credit parameter.


Introducing Modular Architecture

A module is a .py file that encapsulates reusable code, which may include functions, classes, and constants that address a cohesive concern. Python supplies built-in modules, community-contributed third-party packages, and developer-authored custom modules.

Import Strategies

All modules must be imported prior to use. Two common appproaches exist: the import statement and the from ... import ... pattern.

Using a direct import:

import datetime

current_moment = datetime.datetime.now()
print(current_moment)

current_year = current_moment.year
current_month = current_moment.month
print(f"Year: {current_year}, Month: {current_month}")

When importing the entire module, access members using fully qualified names: module_name.class_name.method_name. The datetime module contains a datetime class, whose now() method returns the current date and time. Attributes like year, month, day, hour, minute, and second extract individual components.

Importing specific members:

from datetime import datetime

timestamp = datetime.now()
print(timestamp)

The from ... import ... approach loads specific classes or functions. This allows direct usage without prefixing them with the module name.

Leveraging the Random Toolkit

import random

decimal_value = random.uniform(5.0, 10.0)
print(decimal_value)          # e.g., 7.2148...

throw_dice = random.randint(1, 6)
print(throw_dice)            # random integer from 1 to 6

colors = ["red", "blue", "green"]
picked = random.choice(colors)
print(picked)

The random module offers functions such as:

  • uniform(a, b) – returns a random float in the range [a, b].
  • randint(x, y) – returns a random integer inclusive of both endpoints.
  • choice(sequence) – selects a single random element from a non-empty sequence.

Tags: python Classes Modules Object-Oriented Programming Random

Posted on Fri, 15 May 2026 07:18:34 +0000 by opels