From fb1c692fbaeb012fa4f47bee166f8ef59c7aabd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luiz=20Ot=C3=A1vio?= Date: Sat, 19 Nov 2022 14:05:56 -0300 Subject: [PATCH] =?UTF-8?q?Exemplo=20de=20uso=20de=20dunder=20methods=20(m?= =?UTF-8?q?=C3=A9todos=20m=C3=A1gicos)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- aula147.py | 39 +++++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/aula147.py b/aula147.py index 97aeb5d..d824e21 100644 --- a/aula147.py +++ b/aula147.py @@ -1,7 +1,4 @@ -# Python Dunder Methods __repr__ e __str__ -# Dunder = Double Underscore = __dunder__ -# Antigo e útil: https://rszalski.github.io/magicmethods/ -# https://docs.python.org/3/reference/datamodel.html#specialnames +# Exemplo de uso de dunder methods (métodos mágicos) # __lt__(self,other) - self < other # __le__(self,other) - self <= other # __gt__(self,other) - self > other @@ -16,22 +13,32 @@ # __str__(self) - str # __repr__(self) - str class Ponto: - def __init__(self, x, y, z='String'): + def __init__(self, x, y): self.x = x self.y = y - self.z = z - - def __str__(self): - return f'({self.x}, {self.y})' def __repr__(self): - # class_name = self.__class__.__name__ class_name = type(self).__name__ - return f'{class_name}(x={self.x!r}, y={self.y!r}, z={self.z!r})' + return f'{class_name}(x={self.x!r}, y={self.y!r})' + + def __add__(self, other): + novo_x = self.x + other.x + novo_y = self.y + other.y + novo_ponto = Ponto(novo_x, novo_y) + return novo_ponto + + def __gt__(self, other): + resultado_self = self.x + self.y + resultado_other = other.x + other.y + # print(f'{resultado_self=}') + # print(f'{resultado_other=}') + return resultado_self > resultado_other -p1 = Ponto(1, 2) -p2 = Ponto(978, 876) -print(p1) -print(repr(p2)) -print(f'{p2!r}') +if __name__ == '__main__': + p1 = Ponto(4, 2) + p2 = Ponto(6, 4) + p3 = p1 + p2 + print(p3) + print('P1 é maior que p2', p1 > p2) + print('P2 é maior que p1', p2 > p1)