2016-11-25 5 views
2

Dies ist meine vereinfachte Klassenzuordnung:Python Komplizierte Zahl Multiplikation

class Vector(object): 
    def __init__(self, x, y): 
     self.x = x 
     self.y = y 

class MyComplex(Vector): 
    def __mul__(self, other): 
     return MyComplex(self.real*other.real - self.imag*other.imag, 
         self.imag*other.real + self.real*other.imag) 

    def __str__(self): 
     return '(%g, %g)' % (self.real, self.imag) 

u = MyComplex(2, -1) 
v = MyComplex(1, 2) 

print u * v 

Dies ist die Ausgabe:

"test1.py", line 17, in <module> 
    print u * v 
"test1.py", line 9, in __mul__ 
return MyComplex(self.real*other.real - self.imag*other.imag, 
       self.imag*other.real + self.real*other.imag) 
AttributeError: 'MyComplex' object has no attribute 'real' 

Der Fehler ist klar, aber ich nicht, es herauszufinden, Ihre Hilfe bitte!

Antwort

2

muss der Konstruktor in Vector-Klasse wie folgt ändern:

class Vector(object): 
    def __init__(self, x, y): 
     self.real = x 
     self.imag = y 

Das Problem mit Ihrem Programm war, dass es x und y als Attribute definiert, nicht real und imag, im Konstruktor für Vector Klasse.

1

Es scheint, dass Sie Ihren Initialisierer vergessen haben. Daher haben Instanzen von MyComplex keine Attribute (einschließlich real oder imag). Einfaches Hinzufügen eines Initialisierers zu MyComplex wird Ihr Problem lösen.

def __init__(self, real, imag): 
    self.real = real 
    self.imag = imag 
+0

Es sollte auch darauf hingewiesen werden, dass Sie dadurch die Notwendigkeit vermeiden, dass MyKomplex von "Vector" erbt. – Billylegota

1
def __init__(self, x, y): 
    self.x = x 
    self.y = y 
... 
return MyComplex(self.real*other.real - self.imag*other.imag, 
        self.imag*other.real + self.real*other.imag) 
... 
AttributeError: 'MyComplex' object has no attribute 'real' 

Sie haben nicht Attribut 'real' und 'imag' in Ihrer __init__ Funktion. Sie sollten das Attribut self.x, self.y durch self.real und self.imag ersetzen.