Es. Python tutorial - OOP 2

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

Es. Python tutorial - OOP 2

Versione italiana

Esercizi

11. Classe con Contatore di Oggetti

Crea una classe Book che tenga traccia del numero totale di istanze create utilizzando una variabile di classe.

12. Classe con Metodo Privato

Crea una classe BankAccount con un metodo privato __calculate_interest() che calcola gli interessi su un saldo. Chiama il metodo all’interno della classe.

13. Classe con Metodi di Classe e Istanza

Crea una classe Employee con un metodo di classe set_company() per impostare il nome dell’azienda e un metodo di istanza employee_info() per restituire le informazioni sull’impiegato.

14. Classe con Dunder Method per il Confronto

Crea una classe Rectangle con larghezza e altezza. Implementa __eq__ per confrontare due rettangoli in base all’area.

15. Classe con Iteratore

Crea una classe Counter che implementa __iter__() e __next__() per contare fino a un numero specifico.

16. Classe con Composizione

Crea una classe Engine e una classe Car che abbia un’istanza di Engine come attributo.

17. Classe con Aggregazione

Crea una classe Team che contenga un elenco di oggetti Player, aggiungendo i giocatori al team tramite aggregazione.

18. Classe con Ereditarietà Multipla

Crea due classi Bird e Fish e una classe Penguin che erediti da entrambe.

19. Classe con Proprietà Calcolata

Crea una classe Circle con un raggio e una proprietà area calcolata automaticamente.

20. Classe con Metodo Factory

Crea una classe Person con un metodo di classe from_birth_year() che crei un’istanza partendo dall’anno di nascita.


Soluzioni

# 11. Classe con Contatore di Oggetti
class Book:
    count = 0
    
    def __init__(self, title):
        self.title = title
        Book.count += 1

book1 = Book("1984")
book2 = Book("Brave New World")
print(Book.count)  # Output: 2

# 12. Classe con Metodo Privato
class BankAccount:
    def __init__(self, balance):
        self.balance = balance
    
    def __calculate_interest(self):
        return self.balance * 0.05
    
    def get_interest(self):
        return self.__calculate_interest()

account = BankAccount(1000)
print(account.get_interest())  # Output: 50.0

# 13. Classe con Metodi di Classe e Istanza
class Employee:
    company = "Unknown"
    
    def __init__(self, name):
        self.name = name

    @classmethod
    def set_company(cls, company_name):
        cls.company = company_name

    def employee_info(self):
        return f"{self.name} works at {self.company}"

Employee.set_company("TechCorp")
e1 = Employee("Alice")
print(e1.employee_info())  # Output: Alice works at TechCorp

# 14. Classe con Dunder Method per il Confronto
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def __eq__(self, other):
        return self.area() == other.area()

r1 = Rectangle(4, 5)
r2 = Rectangle(10, 2)
print(r1 == r2)  # Output: True

# 15. Classe con Iteratore
class Counter:
    def __init__(self, max_count):
        self.max_count = max_count
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.max_count:
            raise StopIteration
        self.current += 1
        return self.current

counter = Counter(3)
for num in counter:
    print(num)  # Output: 1 2 3

# 16. Classe con Composizione
class Engine:
    def start(self):
        return "Engine started"

class Car:
    def __init__(self):
        self.engine = Engine()

    def start_car(self):
        return self.engine.start()

car = Car()
print(car.start_car())  # Output: Engine started

# 17. Classe con Aggregazione
class Player:
    def __init__(self, name):
        self.name = name

class Team:
    def __init__(self):
        self.players = []

    def add_player(self, player):
        self.players.append(player)

    def team_info(self):
        return [player.name for player in self.players]

team = Team()
p1 = Player("John")
p2 = Player("David")
team.add_player(p1)
team.add_player(p2)
print(team.team_info())  # Output: ['John', 'David']

# 18. Classe con Ereditarietà Multipla
class Bird:
    def fly(self):
        return "Can fly"

class Fish:
    def swim(self):
        return "Can swim"

class Penguin(Bird, Fish):
    def fly(self):
        return "Cannot fly"

penguin = Penguin()
print(penguin.swim())  # Output: Can swim
print(penguin.fly())   # Output: Cannot fly

# 19. Classe con Proprietà Calcolata
class Circle:
    def __init__(self, radius):
        self.radius = radius

    @property
    def area(self):
        return 3.14 * self.radius ** 2

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

# 20. Classe con Metodo Factory
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_birth_year(cls, name, birth_year):
        return cls(name, 2024 - birth_year)

p = Person.from_birth_year("Mark", 1990)
print(p.name, p.age)  # Output: Mark 34

English version

Exercises

11. Class with Object Counter

Create a class Book that keeps track of the total number of instances created using a class variable.

12. Class with Private Method

Create a class BankAccount with a private method __calculate_interest() that calculates interest on a balance. Call the method inside the class.

13. Class with Class and Instance Methods

Create a class Employee with a class method set_company() to set the company name and an instance method employee_info() to return employee information.

14. Class with Dunder Method for Comparison

Create a class Rectangle with width and height. Implements __eq__ to compare two rectangles based on area.

15. Class with Iterator

Create a class Counter that implements __iter__() and __next__() to count to a specific number.

16. Class with Composition

Create a class Engine and a class Car that has an instance of Engine as an attribute.

17. Class with Aggregation

Create a class Team that contains a list of Player objects, adding players to the team via aggregation.

18. Class with Multiple Inheritance

Create two classes Bird and Fish, and a class Penguin that inherits from both.

19. Class with Calculated Property

Create a class Circle with a radius and an automatically calculated area property.

20. Class with Factory Method

Create a class Person with a class method from_birth_year() that creates an instance starting from the birth year.


Solutions

#11. Class with Object Counter
class Book:
 count = 0

 def __init__(self, title):
 self.title = title
 Book.count += 1

book1 = Book("1984")
book2 = Book("Brave New World")
print(Book.count) # Output: 2

# 12. Class with Private Method
class BankAccount:
 def __init__(self, balance):
 self.balance = balance

 def __calculate_interest(self):
 return self.balance * 0.05

 def get_interest(self):
 return self.__calculate_interest()

account = BankAccount(1000)
print(account.get_interest()) # Output: 50.0

#13. Class with Class and Instance Methods
class Employee:
 company = "Unknown"

 def __init__(self, name):
 self.name = name

 @classmethod
 def set_company(cls, company_name):
 cls.company = company_name

 def employee_info(self):
 return f"{self.name} works at {self.company}"

Employee.set_company("TechCorp")
e1 = Employee("Alice")
print(e1.employee_info()) # Output: Alice works at TechCorp

#14. Class with Dunder Method for Comparison
class Rectangle:
 def __init__(self, width, height):
 self.width = width
 self.height = height

 def area(self):
 return self.width * self.height

 def __eq__(self, other):
 return self.area() == other.area()

r1 = Rectangle(4, 5)
r2 = Rectangle(10, 2)
print(r1 == r2) # Output: True

#15. Class with Iterator
class Counter:
 def __init__(self, max_count):
 self.max_count = max_count
 self.current = 0

 def __iter__(self):
 return self

 def __next__(self):
 if self.current >= self.max_count:
 raise StopIteration
 self.current += 1
 return self.current

counter = Counter(3)
for num in counter:
 print(num) # Output: 1 2 3

#16. Class with Composition
class Engine:
 def start(self):
 return "Engine started"

class Car:
 def __init__(self):
 self.engine = Engine()

 def start_car(self):
 return self.engine.start()

char = Char()
print(car.start_car()) # Output: Engine started

#17. Class with Aggregation
class Player:
 def __init__(self, name):
 self.name = name

class Team:
 def __init__(self):
 self.players = []

 def add_player(self, player):
 self.players.append(player)

 def team_info(self):
 return [player.name for player in self.players]

team = Team()
p1 = Player("John")
p2 = Player("David")
team.add_player(p1)
team.add_player(p2)
print(team.team_info()) # Output: ['John', 'David']

#18. Class with Multiple Inheritance
class Bird:
 def fly(self):
 return "Can fly"

class Fish:
 def swim(self):
 return "Can swim"

class Penguin(Bird, Fish):
 def fly(self):
 return "Cannot fly"

penguin = Penguin()
print(penguin.swim()) # Output: Can swim
print(penguin.fly()) # Output: Cannot fly

# 19. Class with Calculated Property
class Circle:
 def __init__(self, radius):
 self.radius = radius

 @property
 def area(self):
 return 3.14 * self.radius ** 2

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

#20. Class with Factory Method
class Person:
 def __init__(self, name, age):
 self.name = name
 self.age = age

 @classmethod
 def from_birth_year(cls, name, birth_year):
 return cls(name, 2024 - birth_year)

p = Person.from_birth_year("Mark", 1990)
print(p.name, p.age) # Output: Mark 34

Commenti