0
I made this class however, when I enter values that in theory should not be allowed it continues running normally, even having created a function that makes the validation.
I can’t get it inside the builder.
How to validate this data or call the function before the methods I call for the objects are executed.
class Data():
def __init__(self, dia = 1, mes = 1, ano = 1980):
self.__dia = dia
self.__mes = mes
self.__ano = ano
def eAnterior(self, dataComp):
if dataComp.getAno() > self.getAno():
return False
elif dataComp.getAno() == self.getAno() and dataComp.getMes() > self.getMes():
return False
elif dataComp.getAno() == self.getAno() and dataComp.getMes() == self.getMes() and dataComp.getDia() >= self.getDia():
return False
else:
return True
def ePosterior(self, dataComp):
if dataComp.getAno() < self.getAno():
return False
elif dataComp.getAno() == self.getAno() and dataComp.getMes() < self.getMes():
return False
elif dataComp.getAno() == self.getAno() and dataComp.getMes() == self.getMes() and dataComp.getDia() <= self.getDia():
return False
else:
return True
def eSimultaneo(self, dataComp):
if dataComp.getAno() != self.getAno():
return False
elif dataComp.getAno() == self.getAno() and dataComp.getMes() != self.getMes():
return False
elif dataComp.getAno() == self.getAno() and dataComp.getMes() == self.getMes() and dataComp.getDia() != self.getDia():
return False
else:
return True
def _valida(self, dia = 0, mes = 0, ano = 0):
if dia < 1 or dia > 31:
return False
elif mes < 1 or mes > 12:
return False
elif ano < 1:
return False
return True
def setData(self, dia, mes, ano):
if self._valida(dia, mes, ano):
self.setDia(dia)
self.setMes(mes)
self.setAno(ano)
else:
self.setDia(1)
self.setMes(1)
self.setAno(1980)
def __str__(self):
return f'{self.getDia()}/{self.getMes()}/{self.getAno()}'
def getDia(self):
return self.__dia
def setDia(self, dia):
self.__dia = dia
def getMes(self):
return self.__mes
def setMes(self, mes):
self.__mes = mes
def getAno(self):
return self.__ano
def setAno(self, ano):
self.__ano = ano
if __name__ == '__main__':
data = Data('a', 'b', 'c')
print(data)
data2 = Data(27, 9, 1998)
data3 = Data(27, 9, 2015)
if data.eSimultaneo(data3):
print('iguais')
else:
print('diferentes')
In Python we do not use getters and setters. If we need to apply a business rule in these operations we use the property (
@property
). Knows?– Woss
I know, but I still could not use the right way. I mean, I can not use =/
– Haryel Ramalho
There is a reason to create a class and not use the
datetime.date
?– Pedro von Hertwig Batista
yes, academic purposes. @Pedrovonhertwig
– Haryel Ramalho