Construtores alternativos
Python allows you to define class methods as well, using the @classmethod
decorator and a special first argument cls
. The main use of class methods is defining methods that return an instance of the class, but aren't using the same code as __init__()
.
Por exemplo, você está desenvolvendo um pacote de séries temporais e deseja definir sua própria classe para trabalhar com datas, BetterDate
. Os atributos da classe serão year
, month
e day
. Você deseja ter um construtor que crie objetos BetterDate
com os valores de ano, mês e dia, mas também deseja poder criar objetos BetterDate
a partir de strings como 2020-04-30
.
As seguintes funções podem lhe ser úteis:
O método
.split("-")
dividirá uma string em"-"
em uma matriz, por exemplo,"2020-04-30".split("-")
retorna["2020", "04", "30"]
,int()
converterá uma string em um número, por exemplo,int("2019")
é2019
.
Este exercício faz parte do curso
Programação orientada a objetos em Python
Exercício interativo prático
Experimente este exercício preenchendo este código de exemplo.
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)