2016-07-02 7 views
8

Sto tentando di accettare tuple e list come tipi di oggetto in un metodo __add__ in Python. Si prega di consultare il seguente codice:Implementazione di tuple ed elenchi nella funzione isinstance in Python 2.7

class Point(object): 
'''A point on a grid at location x, y''' 
    def __init__(self, x, y): 
     self.X = x 
     self.Y = y 

    def __str__(self): 
     return "X=" + str(self.X) + "Y=" + str(self.Y) 

    def __add__(self, other): 
     if not isinstance(other, (Point, list, tuple)): 
      raise TypeError("Must be of type Point, list, or tuple") 
     x = self.X + other.X 
     y = self.Y + other.Y 
     return Point(x, y) 

p1 = Point(5, 10) 

print p1 + [3.5, 6] 

L'errore che ottengo quando si esegue in Python è:

AttributeError: 'list' object has no attribute 'X' 

Ho semplicemente non riesco a capire il nostro motivo per cui questo non sta funzionando. Questo è compito per un corso universitario e ho pochissima esperienza con Python. So che la funzione isinstance in Python può accettare una tupla di oggetti di tipo, quindi non sono sicuro quale elemento mi manca per gli oggetti tuple e list da accettare. Mi sento come se fosse qualcosa di veramente semplice su cui non mi sto basando.

risposta

3

Se si vuole essere in grado di aggiungere liste o tuple, cambiare il metodo di __add__:

def __add__(self, other): 
    if not isinstance(other, (Point, list, tuple)): 
     raise TypeError("Must be of type Point, list, or tuple") 
    if isinstance(other, (list, tuple)): 
     other = Point(other[0], other[1]) 
    x = self.X + other.X 
    y = self.Y + other.Y 
    return Point(x, y) 

In caso contrario, ci si deve aggiungere un altro oggetto Point , non una lista. In tal caso, basta modificare l'ultima riga:

print p1 + Point(3.5, 6) 
1

Semplice come l'errore che si dice: l'oggetto elenco in python (o probabilmente in qualsiasi lingua non ha attributi x o y). È necessario gestire l'elenco (e tuple anche) caso separatamente