My QA Projects

QA Projects I was involded.

View on GitHub

Encapsulation

class Car:
    def __init__(self, make, model):
        self.__make = make  # Private attribute
        self.__model = model  # Private attribute

    def get_make(self):
        return self.__make

    def set_make(self, make):
        self.__make = make

    def get_model(self):
        return self.__model

    def set_model(self, model):
        self.__model = model

# Usage
my_car = Car("Toyota", "Camry")
print(my_car.get_make())  # Output: Toyota
print(my_car.get_model())  # Output: Camry

my_car.set_make("Honda")
my_car.set_model("Accord")
print(my_car.get_make())  # Output: Honda
print(my_car.get_model())  # Output: Accord

# Directly accessing private attributes raises an error
# print(my_car.__make)  # This line raises an AttributeError

# Example 2


class Car:
    def __init__(self, make, model, year):
        self.__make = make  # private attribute
        self.__model = model  # private attribute
        self.__year = year  # private attribute
        self.__odometer_reading = 0  # private attribute

    def get_make(self):
        return self.__make

    def get_model(self):
        return self.__model

    def get_year(self):
        return self.__year

    def get_odometer_reading(self):
        return self.__odometer_reading

    def set_odometer_reading(self, mileage):
        if mileage >= self.__odometer_reading:
            self.__odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")

    def drive(self, miles):
        print(f"The car has driven {miles} miles.")
        self.__update_odometer(miles)

    def __update_odometer(self, miles):
        self.__odometer_reading += miles


# Creating an instance of Car
my_car = Car("Toyota", "Corolla", 2020)

# Accessing public methods to interact with private attributes
print(f"My car is a {my_car.get_year()} {my_car.get_make()} {my_car.get_model()}.")

# Using encapsulated methods to update and access private attribute
my_car.drive(100)
print(f"Current odometer reading: {my_car.get_odometer_reading()} miles.")

# Trying to directly access a private attribute (will raise an error)
# print(my_car.__odometer_reading)  # This line will raise an AttributeError