Es. Python tutorial - OOP

Es. Python tutorial - OOP Es. Python tutorial - OOP

Es. Python tutorial - OOP

Versione italiana

Esercizi

1. Creazione di una Classe

Crea una classe Car con gli attributi brand, model e year. Istanzia un oggetto Car e stampa i suoi attributi.

2. Metodi di una Classe

Aggiungi un metodo car_info() alla classe Car che restituisce una stringa con le informazioni dell’auto. Creane un’istanza e chiama il metodo.

3. Incapsulamento con Attributi Privati

Modifica la classe Car rendendo year un attributo privato. Aggiungi un metodo get_year() per accedervi.

4. Metodi __str__ e __repr__

Modifica la classe Car aggiungendo il metodo __str__ per restituire una rappresentazione leggibile dell’oggetto.

5. Ereditarietà

Crea una classe ElectricCar che erediti da Car e aggiungi un attributo battery_capacity. Creane un’istanza e stampa le sue informazioni.

6. Override di Metodi

Nella classe ElectricCar, sovrascrivi il metodo car_info() per includere anche la capacità della batteria.

7. Uso di super()

Modifica la classe ElectricCar e usa super() nel metodo __init__() per chiamare il costruttore della classe padre.

8. Classe con Metodo Statico

Aggiungi un metodo statico is_classic(year) alla classe Car che restituisce True se l’auto ha più di 30 anni.

9. Uso di Proprietà con @property e @setter

Rendi l’attributo year una proprietà con un metodo getter e setter.

10. Classe con Metodo di Classe

Aggiungi un metodo di classe from_string(cls, car_string) alla classe Car che crea un’istanza partendo da una stringa nel formato "brand,model,year".


Soluzioni

# 1. Creazione di una Classe
class Car:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.year = year

# script.py
car = Car("Toyota", "Corolla", 2020)
print(car.brand, car.model, car.year)  # Output: Toyota Corolla 2020

# 2. Metodi di una Classe
class Car:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.year = year

    def car_info(self):
        return f"{self.brand} {self.model}, Year: {self.year}"

car = Car("Ford", "Focus", 2018)
print(car.car_info())  # Output: Ford Focus, Year: 2018

# 3. Incapsulamento con Attributi Privati
class Car:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.__year = year  # Attributo privato

    def get_year(self):
        return self.__year

car = Car("Honda", "Civic", 2015)
print(car.get_year())  # Output: 2015

# 4. Metodi `__str__` e `__repr__`
class Car:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.year = year

    def __str__(self):
        return f"Car({self.brand}, {self.model}, {self.year})"

car = Car("Mazda", "CX-5", 2022)
print(car)  # Output: Car(Mazda, CX-5, 2022)

# 5. Ereditarietà
class ElectricCar(Car):
    def __init__(self, brand, model, year, battery_capacity):
        super().__init__(brand, model, year)
        self.battery_capacity = battery_capacity

electric_car = ElectricCar("Tesla", "Model S", 2023, "100 kWh")
print(electric_car.brand, electric_car.model, electric_car.battery_capacity)  # Output: Tesla Model S 100 kWh

# 6. Override di Metodi
class ElectricCar(Car):
    def __init__(self, brand, model, year, battery_capacity):
        super().__init__(brand, model, year)
        self.battery_capacity = battery_capacity

    def car_info(self):
        return f"{self.brand} {self.model}, Year: {self.year}, Battery: {self.battery_capacity}"

electric_car = ElectricCar("Nissan", "Leaf", 2021, "40 kWh")
print(electric_car.car_info())  # Output: Nissan Leaf, Year: 2021, Battery: 40 kWh

# 7. Uso di `super()`
class ElectricCar(Car):
    def __init__(self, brand, model, year, battery_capacity):
        super().__init__(brand, model, year)
        self.battery_capacity = battery_capacity

electric_car = ElectricCar("BMW", "i3", 2022, "42 kWh")
print(electric_car.car_info())  # Output: BMW i3, Year: 2022, Battery: 42 kWh

# 8. Classe con Metodo Statico
class Car:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.year = year

    @staticmethod
    def is_classic(year):
        return 2024 - year > 30

print(Car.is_classic(1990))  # Output: True
print(Car.is_classic(2010))  # Output: False

# 9. Uso di Proprietà con `@property` e `@setter`
class Car:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self._year = year

    @property
    def year(self):
        return self._year

    @year.setter
    def year(self, new_year):
        if new_year > 1885:  # La prima auto è stata inventata nel 1886
            self._year = new_year
        else:
            raise ValueError("Anno non valido!")

car = Car("Audi", "A4", 2019)
print(car.year)  # Output: 2019
car.year = 2022
print(car.year)  # Output: 2022

# 10. Classe con Metodo di Classe
class Car:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.year = year

    @classmethod
    def from_string(cls, car_string):
        brand, model, year = car_string.split(",")
        return cls(brand, model, int(year))

car = Car.from_string("Ferrari,488,2020")
print(car.brand, car.model, car.year)  # Output: Ferrari 488 2020

English version

Exercises

1. Creating a Class

Create a Car class with the attributes brand, model, and year. Instantiate a Car object and print its attributes.

2. Methods of a Class

Add a car_info() method to the Car class that returns a string with the car’s information. Create an instance of it and call the method.

3. Encapsulation with Private Attributes

Modify the Car class to make year a private attribute. Add a get_year() method to access it.

4. __str__ and __repr__ Methods

Modify the Car class to add the __str__ method to return a human-readable representation of the object.

5. Inheritance

Create a class ElectricCar that inherits from Car and add a battery_capacity attribute. Create an instance of it and print its information.

6. Overriding Methods

In the ElectricCar class, override the car_info() method to include the battery capacity.

7. Using super()

Modify the ElectricCar class and use super() in the __init__() method to call the parent class’s constructor.

8. Class with Static Method

Add a static method is_classic(year) to the Car class that returns True if the car is older than 30 years.

9. Using Properties with @property and @setter

Make the year attribute a property with a getter and setter method.

10. Class with Class Method

Add a class method from_string(cls, car_string) to the Car class that creates an instance from a string of the format "brand,model,year".


Solutions

#1. Creating a Class
class Car:
 def __init__(self, brand, model, year):
 self.brand = brand
 self.model = model
 self.year = year

# script.py
car = Car("Toyota", "Corolla", 2020)
print(car.brand, car.model, car.year) # Output: Toyota Corolla 2020

#2. Methods of a Class
class Car:
 def __init__(self, brand, model, year):
 self.brand = brand
 self.model = model
 self.year = year

 def car_info(self):
 return f"{self.brand} {self.model}, Year: {self.year}"

car = Car("Ford", "Focus", 2018)
print(car.car_info()) # Output: Ford Focus, Year: 2018

#3. Encapsulation with Private Attributes
class Car:
 def __init__(self, brand, model, year):
 self.brand = brand
 self.model = model
 self.__year = year # Private attribute

 def get_year(self):
 return self.__year

car = Car("Honda", "Civic", 2015)
print(car.get_year()) # Output: 2015

# 4. `__str__` and `__repr__` methods
class Car:
 def __init__(self, brand, model, year):
 self.brand = brand
 self.model = model
 self.year = year

 def __str__(self):
 return f"Char({self.brand}, {self.model}, {self.year})"

car = Car("Mazda", "CX-5", 2022)
print(char) # Output: Car(Mazda, CX-5, 2022)

#5. Heredity
class ElectricCar(Car):
 def __init__(self, brand, model, year, battery_capacity):
 super().__init__(brand, model, year)
 self.battery_capacity = battery_capacity

electric_car = ElectricCar("Tesla", "Model S", 2023, "100 kWh")
print(electric_car.brand, electric_car.model, electric_car.battery_capacity) # Output: Tesla Model S 100 kWh

#6. Overriding Methods
class ElectricCar(Car):
 def __init__(self, brand, model, year, battery_capacity):
 super().__init__(brand, model, year)
 self.battery_capacity = battery_capacity

 def car_info(self):
 return f"{self.brand} {self.model}, Year: {self.year}, Battery: {self.battery_capacity}"

electric_car = ElectricCar("Nissan", "Leaf", 2021, "40 kWh")
print(electric_car.car_info()) # Output: Nissan Leaf, Year: 2021, Battery: 40 kWh

#7. Using `super()`
class ElectricCar(Car):
 def __init__(self, brand, model, year, battery_capacity):
 super().__init__(brand, model, year)
 self.battery_capacity = battery_capacity

electric_car = ElectricCar("BMW", "i3", 2022, "42 kWh")
print(electric_car.car_info()) # Output: BMW i3, Year: 2022, Battery: 42 kWh

# 8. Class with Static Method
class Car:
 def __init__(self, brand, model, year):
 self.brand = brand
 self.model = model
 self.year = year

 @staticmethod
 def is_classic(year):
 return 2024 - year > 30

print(Car.is_classic(1990)) # Output: True
print(Car.is_classic(2010)) # Output: False
#9. Using Properties with `@property` and `@setter`
class Car:
 def __init__(self, brand, model, year):
 self.brand = brand
 self.model = model
 self._year = year

 @property
 def year(self):
 return self._year

 @year.setter
 def year(self, new_year):
 if new_year > 1885: # The first car was invented in 1886
 self._year = new_year
 else:
 raise ValueError("Invalid year!")

car = Car("Audi", "A4", 2019)
print(car.year) # Output: 2019
car.year = 2022
print(car.year) # Output: 2022

#10. Class with Class Method
class Car:
 def __init__(self, brand, model, year):
 self.brand = brand
 self.model = model
 self.year = year

 @classmethod
 def from_string(cls, car_string):
 brand, model, year = car_string.split(",")
 return cls(brand, model, int(year))

car = Car.from_string("Ferrari,488,2020")
print(car.brand, car.model, car.year) # Output: Ferrari 488 2020

Commenti