TransitCard: Object-Oriented Python Programming
PythonObject-Oriented ProgrammingClassesError HandlingUnit Testing
Project Overview
This project implements a TransitCard class in Python that simulates a transit fare card system. The implementation demonstrates core object-oriented programming concepts including class definition, constructor methods, instance methods, error handling, and object representation. The TransitCard has features for balance management, ride fare deduction, and validation rules to prevent invalid transactions.
Date: March 2025
Implementation Details
TransitCard Class Structure
classDiagram
class TransitCard {
+MAX_TRANSACTION: float
-balance_value: float
-max_balance: float
+__init__(amount)
+ride(fare)
+addValue(amount)
+balance()
+__repr__()
}
TransitCard Class Implementation
#Laurentiu Mandocescu
class TransitCard:
MAX_TRANSACTION = 100.00 # class variable for maximum transaction amount
def __init__(self, amount=5):
"""Initialize TransitCard with balance up to 100.00, default is 5."""
if amount > self.MAX_TRANSACTION:
raise ValueError('Amount is > 100.00')
self.balance_value = float(amount)
self.max_balance = 350.00
def ride(self, fare):
"""Deduct fare from balance if allowed; otherwise raise error."""
if self.balance_value <= 0:
raise ValueError('Card balance is 0 or negative; ride is denied')
self.balance_value -= fare
def addValue(self, amount):
"""Add amount to balance if valid; otherwise raise error."""
if amount > self.MAX_TRANSACTION:
raise ValueError('Amount is > 100.00')
if self.balance_value + amount > self.max_balance:
raise ValueError('Card balance will be greater than 350.00; request is denied')
self.balance_value += amount
def balance(self):
"""Return the current balance."""
return self.balance_value
def __repr__(self):
"""Return a canonical representation of the object."""
return "The card balance is " + str(self.balance_value)
Unit Testing
def testTransitCard():
# Test __init__ and __repr__
try:
card_default = TransitCard()
print(repr(card_default))
card_param = TransitCard(50)
print(repr(card_param))
try:
TransitCard(150)
except ValueError as e:
print(e)
except Exception as e:
print("Error in __init__ tests:", e)
# Test ride method
try:
card = TransitCard(20)
card.ride(10)
print(card.balance())
card.ride(15)
print(card.balance())
try:
card.ride(5)
except ValueError as e:
print(e)
except Exception as e:
print("Error in ride tests:", e)
# Test addValue method
try:
card2 = TransitCard(100)
card2.addValue(50)
print(card2.balance())
try:
card2.addValue(150)
except ValueError as e:
print(e)
card3 = TransitCard(300)
try:
card3.addValue(60)
except ValueError as e:
print(e)
except Exception as e:
print("Error in addValue tests:", e)
if __name__ == '__main__':
testTransitCard()
Key Features
- Default Balance: Cards initialize with a default balance of $5.00 if no amount is specified.
- Transaction Limits: Single transactions cannot exceed $100.00 to prevent fraud or errors.
- Maximum Balance: Card balance cannot exceed $350.00 for security and compliance reasons.
- Ride Validation: Denies rides when balance is zero or negative with appropriate error messages.
- Error Handling: Comprehensive error handling with descriptive messages for all exceptional conditions.
- Clean API: Simple interface with just three main methods: ride(), addValue(), and balance().
Object-Oriented Concepts
- Encapsulation: Internal balance state is protected and accessed only through well-defined methods.
- Constructor Method: __init__ method initializes the object with parameters and default values.
- Instance Methods: Methods that operate on the object's state (ride, addValue, balance).
- Class Variables: MAX_TRANSACTION is shared across all instances of the class.
- String Representation: __repr__ method provides a clear string representation of the object.
- Docstrings: Comprehensive documentation for each method describing purpose and behavior.
Test Results
When running the test function, the following output is produced:
The card balance is 5.0
The card balance is 50.0
Amount is > 100.00
10.0
-5.0
Card balance is 0 or negative; ride is denied
150.0
Amount is > 100.00
Card balance will be greater than 350.00; request is denied
Learning Outcomes
This project demonstrates several key programming concepts and skills:
- Implementation of classes and objects in Python
- Designing appropriate error handling mechanisms
- Developing intuitive method APIs with sensible defaults
- Writing effective unit tests to validate class behavior
- Documentation using docstrings and clear naming conventions
- Implementing business logic with proper validation rules