'list'属性没有属性<function> </function>

时间:2013-12-05 21:20:26

标签: python

我正在尝试为包含在列表上运行的函数的复数创建一个类。我认为我的基本设置是可以的,因为它适用于对单个元素(如共轭)进行操作的函数,但是当我尝试运行像conjugateList这样的函数时,我得到错误消息“'list'对象没有属性'conjugateList'。我我不知道如何解决这个问题。谢谢。

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

2 个答案:

答案 0 :(得分:1)

由于conjugateList方法不在您的列表中,因此它位于Complex对象上。

请注意,此conjugateList方法实际上应该是staticmethod或 - 更好 - 一个函数。

你会这样做:

class Complex():    
    # The rest of your stuff

    @staticmethod
    def conjugateList(lstC):
        newLst = []
        for elem in lstC:
            elem = elem.conjugate()
            newLst += elem
        return newLst

然后,

l1 = [Complex(1,1), Complex(1,2)]
l2 = Complex.conjugateList(l1)

答案 1 :(得分:0)

缺乏课堂设计的学习目的,对于制作,您可能需要使用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])
相关问题