Frage

Please look at the code below and the Attribute error I get. Thanks for your help.

This is the error I get.

Traceback (most recent call last):
    File "ClassError.py", line 45, in <module>
    if __name__ == '__main__':Main()
File "ClassError.py", line 43, in Main
    printTest(i)
File "ClassError.py", line 38, in printTest
    print f.FirstName
AttributeError: 'str' object has no attribute 'FirstName'

CODE

class CompKeyData():
    def __init__(self,
        FirstName,\
        MiddleName,\
        LastName):
        self.FirstName  = FirstName
        self.MiddleName = MiddleName
        self.LastName   = LastName

    def __repr__(self):
        return repr((self.FirstName,\
                     self.MiddleName,\
                     self.LastName))

    def __iter__(self): 
        return iter((self.FirstName,\
                     self.MiddleName,\
                     self.LastName))

def ckDataClassList(dataList):
    dataObjects = []
    for FirstName,\
        MiddleName,\
        LastName in dataList:
        dataObjects.append(CompKeyData(
            FirstName,\
            MiddleName,\
            LastName))
    return dataObjects

ckData = [['John', 'Ralph', 'DuMont'], ['Jack', 'Lowry', 'Matern']] 

ckClassData = ckDataClassList(ckData)


def printTest(classData):
    for f in classData:
    print f.FirstName
return None

def Main():
    for i in ckClassData:
    printTest(i)

if __name__ == '__main__':Main()    
War es hilfreich?

Lösung

When you do

for i in ckClassData:

Each i is a CompKeyData instance. You then do:

printTest(i)

Which calls:

for f in classData:

where classData is the i you passed in.

This iterates through the individual CompKeyData instance, which (due to your implementation of __iter__) assigns FirstName, MiddleName and LastName in turn to f- each of these is a string, and doesn't have FirstName.

Instead, printTest should be:

printTest(classData):
    print classData.FirstName

You don't need to explicitly return None, this happens automatically if you don't explicitly return anything else.

Also, it is worth reading PEP-0008; following this will make your code more readable.

Andere Tipps

You need to change your printTest function to the following:

def printTest(classData):
    print classData.FirstName

classData is not a list of CompKeyData instances, but rather a single CompKeyData instance.

PEP8 is also certainly worth a look for python style.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top