Created
January 21, 2021 22:19
-
-
Save Abathargh/cab2a81bf2739a79b7e36a660a51d313 to your computer and use it in GitHub Desktop.
Esempi trattati nell'articolo di antima.it raggiungibile al seguente link https://antima.it/elementi-di-python-utilizzi-pratici-dei-metodi-dunder/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Arduino: | |
def __init__(self, nome, microcontr): | |
self._nome = nome | |
self._microcontr = microcontr | |
def __str__(self): | |
return f"Arduino {self._nome}" | |
def __repr__(self): | |
return f"Arduino(nome={self._nome}, microcontr={self._microcontr})" | |
uno = Arduino("Uno", "ATmega328") | |
nano = Arduino("Nano", "ATmega328p") | |
print("print usando __str__", uno, "-", nano) | |
print("print usando __repr__", repr(uno), "-", repr(nano)) | |
# Utilizzo implicito di repr e str con str.format | |
print("print usando __str__ {} - {}".format(uno, nano)) | |
print("print usando __repr__ {!r} - {!r}".format(uno, nano)) | |
# Utilizzo implicito di repr e str con le f-string (python >= 3.6) | |
print(f"print usando __str__ {uno} - {nano}") | |
print(f"print usando __repr__ {uno!r} - {nano!r}") | |
class Raspberry: | |
def __init__(self, modello): | |
self._modello = modello | |
def __repr__(self): | |
return f"Raspberry(modello={self._modello})" | |
def __eq__(self, other): | |
if not isinstance(other, Raspberry): | |
return NotImplemented | |
return self._modello == other._modello | |
def __hash__(self): | |
return hash(self._modello) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment