Metodi magici in Python
Livello 4246 battiture
Questo implementa metodi magici per l'overloading degli operatori. __add__ abilita l'operatore + e __repr__ definisce la rappresentazione stringa.
Codice Python
# Definisce una classe Vector con metodi magici1class Vector: # Inizializza con coordinate x e y2 def __init__(self, x, y): # Spacchettamento di tupla per assegnare x e y3 self.x, self.y = x, y # __add__ è chiamato quando si usa l'operatore +4 def __add__(self, other): # Restituisce un nuovo Vector con le coordinate sommate5 return Vector(self.x + other.x, self.y + other.y) # __repr__ restituisce la rappresentazione come stringa6 def __repr__(self): # Restituisce una stringa formattata con le coordinate7 return f"Vector({self.x}, {self.y})"8 # Crea il primo vettore (1, 2)9v1 = Vector(1, 2)# Crea il secondo vettore (3, 4)10v2 = Vector(3, 4)# Somma i vettori con l'operatore + e stampa Vector(4, 6)11print(v1 + v2)Output
Vector(4, 6)
Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.
Simboli in questo codice
I simboli che digiti in questo codice Python e quante volte compaiono.
_× 12,× 9.× 8(× 8)× 8:× 4+× 3=× 3"× 2{× 2