Access Control, Abstract Classes, Interfaces,

Published Sept. 7, 2023, 2:24 p.m.

Python's OOP Mastery: Access Control, Abstract Classes, Interfaces, and Custom Object Representations

OUTLINE: 

1. Abstract Method
2. Abstract Class
3. Interface
4. Public, Private, and Protected Members
5. `str()` Method
6. Difference between `str()` and `repr()` Functions
7. Small Airlines Application

1. Abstract Method 🎨

An abstract method serves as a blueprint for a function within a class. It is declared within a class but lacks an implementation in that class. Instead, it must be defined in any subclass inheriting from this class.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius * self.radius

circle = Circle(5)
print(circle.area())  # Output: 78.5

In this example, 🎨 Shape is an abstract class featuring an abstract method, area(). The 🌀 Circle class inherits from Shape and provides an implementation of the area() method.

2. Abstract Class 🖌️

An abstract class cannot be instantiated on its own and typically contains one or more abstract methods. Its purpose is to be subclassed to provide concrete implementations.

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

dog = Dog()
print(dog.speak())  # Output: Woof!

In this example, 🖌️ Animal is an abstract class featuring an abstract method, speak(). The 🐕 Dog class inherits from Animal and provides a concrete implementation of the speak() method.

3. Interface 🛤️

An interface defines a contract for classes implementing it, specifying a set of methods that must be implemented by any adhering class.

from abc import ABC, abstractmethod

class Drawable(ABC):
    @abstractmethod
    def draw(self):
        pass

class Circle(Drawable):
    def draw(self):
        return "Drawing a circle"

circle = Circle()
print(circle.draw())  # Output: Drawing a circle

In this example, 🛤️ Drawable is an interface featuring a single abstract method, draw(). The ⭕ Circle class implements the Drawable interface by providing a concrete draw() method.

4. Public, Private, and Protected Members 🚀

Python allows class members (attributes and methods) to have different access levels. Public members are accessible from anywhere, protected members are accessible only within the class, and private members are accessible within the class and its subclasses.

class MyClass:
    def __init__(self):
        self.public_var = "I'm public"
        self._protected_var = "I'm protected"
        self.__private_var = "I'm private"

    def public_method(self):
        return "This is a public method"

    def _protected_method(self):
        return "This is a protected method"

    def __private_method(self):
        return "This is a private method"


obj = MyClass()
print(obj.public_var)  # Output: I'm public
print(obj._protected_var)  # Output: I'm protected
print(obj._MyClass__private_var)  # Output: I'm private

In this example, we observe 🚀 public, protected, and private members, along with methods. Python employs name mangling for private members to restrict their accessibility.

5. str() Method 📜

The str() method serves to obtain a string representation of an object and is often customized by defining the __str__() method within a class.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name}, {self.age} years old"

person = Person("Alice", 30)
print(str(person))  # Output: Alice, 30 years old

In this example, the 📜 __str__() method is defined to provide a customized string representation for the Person class.

6. Difference between str() and repr() Functions 📊

Both str() and repr() convert an object into a string, but they serve distinct purposes. str() aims for a user-friendly, informative string, while repr() is intended for debugging and should be unambiguous.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"Point({self.x}, {self.y})"

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

point = Point(3, 4)

# Using str() for a user-friendly string
print(str(point))  # Output: Point(3, 4)

# Using repr() for debugging
print(repr(point))  # Output: Point(3, 4)

In this example, str() provides a user-friendly string, while repr() offers an unambiguous object representation for debugging purposes.

7. Small Airlines Application ✈️

An enhanced small airlines application simulates basic airline operations, including booking flights, managing passengers, and displaying flight details.

In this enhanced airlines application, you can book tickets, display flight details, and exit the application. It can handle multiple user inputs and offers an interactive experience. Feel free to explore the options and enjoy your flight! 🛫

class Flight:
    def __init__(self, flight_number, destination, capacity):
        # Initialize flight attributes
        self.flight_number = flight_number
        self.destination = destination
        self.capacity = capacity
        self.passengers = []

    def book_ticket(self, passenger_name):
        # Book a ticket for a passenger
        if len(self.passengers) < self.capacity:
            self.passengers.append(passenger_name)
            return f"Ticket booked for {passenger_name}"
        else:
            return "Sorry, the flight is full."

    def display_details(self):
        # Display flight details including the number of passengers
        return f"Flight {self.flight_number} to {self.destination} with {len(self.passengers)} passengers."

# Welcome message
print("Welcome to the Enhanced Small Airlines Application!")

# Create a flight
flight1 = Flight("F001", "New York", 100)

while True:
    print("\nOptions:")
    print("1. Book a ticket")
    print("2. Display flight details")
    print("3. Exit")
    choice = input("Enter your choice (1/2/3): ")

    if choice == "1":
        # Option 1: Book a ticket
        passenger_name = input("Enter passenger name: ")
        result = flight1.book_ticket(passenger_name)
        print(result)
    elif choice == "2":
        # Option 2: Display flight details
        details = flight1.display_details()
        print(details)
    elif choice == "3":
        # Option 3: Exit the application
        print("Thank you for using the Enhanced Small Airlines Application!")
        break
    else:
        # Invalid choice
        print("Invalid choice. Please select a valid option.")
  1. Open a text editor or an integrated development environment (IDE) like Visual Studio Code or PyCharm.

  2. Paste the code into a new Python file (e.g., airlines_app.py).

  3. Save the file.

  4. Open a terminal or command prompt.

  5. Navigate to the directory where you saved the Python file.

  6. Run the Python file using the command python airlines_app.py.

  7. Follow the prompts and input your choices, passenger names, and other details as instructed by the application.

First Run:

Welcome to the Enhanced Small Airlines Application!

Options:
1. Book a ticket
2. Display flight details
3. Exit
Enter your choice (1/2/3): 1
Enter passenger name: Alice
Ticket booked for Alice

Options:
1. Book a ticket
2. Display flight details
3. Exit
Enter your choice (1/2/3): 1
Enter passenger name: Bob
Ticket booked for Bob

Options:
1. Book a ticket
2. Display flight details
3. Exit
Enter your choice (1/2/3): 2
Flight F001 to New York with 2 passengers.

Options:
1. Book a ticket
2. Display flight details
3. Exit
Enter your choice (1/2/3): 3
Thank you for using the Enhanced Small Airlines Application!

Second Run:

Welcome to the Enhanced Small Airlines Application!

Options:
1. Book a ticket
2. Display flight details
3. Exit
Enter your choice (1/2/3): 1
Enter passenger name: Carol
Ticket booked for Carol

Options:
1. Book a ticket
2. Display flight details
3. Exit
Enter your choice (1/2/3): 2
Flight F001 to New York with 3 passengers.

Options:
1. Book a ticket
2. Display flight details
3. Exit
Enter your choice (1/2/3): 3
Thank you for using the Enhanced Small Airlines Application!

In the first run, we booked tickets for Alice and Bob, and in the second run, we booked a ticket for Carol. The application displays the total number of passengers on the flight. You can continue to run the application and book tickets with different passenger names as needed.