~ 4 min read

Python Classes for Storing and Managing Variables

By: Adam Richardson
Share:

Python Classes for Storing and Managing Variables

Introduction

In this article, we will discuss the benefits of using Python classes to store and manage variables. Classes allow you to organize your code efficiently and make it more maintainable. By using classes, you can encapsulate related data and behaviors, making your code modular and easy to understand.

Python Class Properties and Usage

A Python class is a code template for creating objects. Objects have member variables and behavior associated with them. In Python, a class can have properties (variables) and methods (functions).

To define a class, we use the class keyword followed by the class name and a colon. The properties and methods should be indented to be part of the class. To create an instance of a class, simply call the class name followed by parentheses.

Properties

Properties are defined within a class using the property’s name and an initial value in most cases. To access a property, use the dot notation, e.g., object.property_name. Properties can be of any Python data type.

Methods

Methods are functions defined within a class. They have access to the instance and its properties. To declare a method, use the def keyword followed by the method name and a pair of parentheses. The first parameter of any method should be self, which refers to the instance of the class. Like in properties, to access a method, use the dot notation, e.g., object.method_name().

Simplified Real-life Example

Let’s see how to utilize Python classes in a simple real-life scenario. Suppose you are working on a project that processes users, their emails, and preferred email subscriptions.

class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.subscriptions = []

    def subscribe(self, subscription_name):
        self.subscriptions.append(subscription_name)

    def display_user(self):
        print(f"Name: {self.name}")
        print(f"Email: {self.email}")
        print("Subscriptions:", ", ".join(self.subscriptions))

# Create a user instance
user1 = User("John Doe", "john.doe@email.com")

# Add subscriptions and display user
user1.subscribe("Tech News")
user1.subscribe("Travel Deals")
user1.display_user()

In this example, we define a User class with properties name, email, and subscriptions. We also define two methods, subscribe for adding subscriptions, and display_user for displaying user information. This code creates a user and adds subscriptions, then displays the user’s information.

Complex Real-life Example

Now, let’s look at a more complex example. Suppose we need to create a system that manages different bank accounts, including checking and savings.

class BankAccount:
    def __init__(self, account_type, balance=0):
        self.account_type = account_type
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print(f"{amount} deposited. Current balance: {self.balance}")

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
            print(f"{amount} withdrawn. Current balance: {self.balance}")
        else:
            print("Insufficient balance")

class Customer:
    def __init__(self, name, checking_account, savings_account):
        self.name = name
        self.checking_account = checking_account
        self.savings_account = savings_account

    def transfer_funds(self, source_account, target_account, amount):
        if source_account.balance >= amount:
            source_account.withdraw(amount)
            target_account.deposit(amount)
        else:
            print("Insufficient balance in source account")

# Create accounts
checking_account = BankAccount("Checking", 1000)
savings_account = BankAccount("Savings", 2000)

# Create a customer with accounts
customer1 = Customer("Jane Smith", checking_account, savings_account)

# Perform some transactions
customer1.checking_account.deposit(500)
customer1.savings_account.withdraw(300)
customer1.transfer_funds(customer1.checking_account, customer1.savings_account, 200)

In this example, we have two classes, BankAccount and Customer. The BankAccount class has properties for the account type and balance, and methods for depositing, withdrawing, and transferring funds. The Customer class has properties for the customer’s name, checking account, and savings account, and a method for transferring funds between accounts.

Personal Tips

  1. Keep your classes focused on a single responsibility. This makes them easy to understand and maintain.

  2. Use descriptive names for your classes, properties, and methods to make your code self-documenting.

  3. Encapsulate code that changes for the same reasons to separate classes or methods.

  4. Leverage inheritance and composition to create reusable and extendable solutions.

By following these tips and applying the concepts discussed in this article, you can effectively use Python classes to organize your code, making it more modular, maintainable, and understandable.

Share:
Subscribe to our newsletter

Stay up to date with our latest content - No spam!

Related Posts