IniziaInizia gratis

Costruttori alternativi

Python ti permette di definire anche i metodi di classe, usando il decoratore @classmethod e un primo argomento speciale cls. L’uso principale dei metodi di classe è definire metodi che restituiscono un’istanza della classe, ma senza usare lo stesso codice di __init__().

Per esempio, stai sviluppando un pacchetto per serie temporali e vuoi definire una tua classe per lavorare con le date, BetterDate. Gli attributi della classe saranno year, month e day. Vuoi avere un costruttore che crei oggetti BetterDate dati i valori di year, month e day, ma vuoi anche poter creare oggetti BetterDate a partire da stringhe come 2020-04-30.

Potrebbero esserti utili le seguenti funzioni:

  • Il metodo .split("-") divide una stringa su "-" in un array, ad esempio "2020-04-30".split("-") restituisce ["2020", "04", "30"],
  • int() converte una stringa in un numero, ad esempio int("2019") è 2019 .

Questo esercizio fa parte del corso

Programmazione orientata agli oggetti in Python

Visualizza il corso

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

class BetterDate:    
    # Constructor
    def __init__(self, year, month, day):
      # Recall that Python allows multiple variable assignments in one line
      self.year, self.month, self.day = year, month, day
    
    # Define a class method from_str
    ____
    def from_str(____, datestr):
        # Split the string at "-" and convert each part to integer
        parts = datestr.split("-")
        year, month, day = int(parts[0]), ____, ____
        # Return the class instance
        ____ ____(____, ____, ____)
        
bd = BetterDate.from_str('2020-04-30')   
print(bd.year)
print(bd.month)
print(bd.day)
Modifica ed esegui il codice