Reputation: 1
I am trying to create a class for Complex numbers that includes functions that operate on lists. I think my basic setup is okay because it works for functions that operate on single elements(like conjugate), but when I try to run functions like conjugateList, I get the error message "'list' object has no attribute 'conjugateList'. I am not sure how to address this problem. Thanks.
class Complex():
def __init__(self, real= 0.0, imaginary= 0.0):
self.real = real
self.imaginary = imaginary
def __str__(self):
if self.imaginary < 0:
printStr = str(self.real) + ' - ' + str(abs(self.imaginary))+ 'i'
else:
printStr = str(self.real) + ' + ' + str(self.imaginary)+ 'i'
return printStr
def conjugate(self):
result = Complex()
result.real = self.real
result.imaginary = (self.imaginary * (-1))
return result
def conjugateList(lstC):
newLst = []
for elem in lstC:
elem = elem.conjugate()
newLst += elem
return newLst
Upvotes: 0
Views: 736
Reputation: 142226
Short of learning purposes for class design, for production you might want to use numpy
:
>>> import numpy as np
>>> comps = np.array([complex(1, 1), complex(1, 2)])
>>> comps.dtype
dtype('complex128')
>>> comps.conjugate()
array([ 1.-1.j, 1.-2.j])
Upvotes: 0
Reputation: 55303
Because the conjugateList
method isn't on your list, it's on the Complex
object.
Note that this conjugateList
method should actually be a staticmethod
or — better yet — a function.
You would do:
class Complex():
# The rest of your stuff
@staticmethod
def conjugateList(lstC):
newLst = []
for elem in lstC:
elem = elem.conjugate()
newLst += elem
return newLst
And then,
l1 = [Complex(1,1), Complex(1,2)]
l2 = Complex.conjugateList(l1)
Upvotes: 1