Exemplo de uso de dunder methods (métodos mágicos)

This commit is contained in:
Luiz Otávio
2022-11-19 14:05:56 -03:00
parent 5b41d8b102
commit fb1c692fba

View File

@@ -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)