Attribute error-- but I'm innocent(?)

John Machin sjmachin at lexicon.net
Mon Mar 2 20:15:43 EST 2009


On Mar 3, 11:56 am, Nick Mellor <nick.mellor.gro... at pobox.com> wrote:
> Hi all,
>
> I'm pretty sure I'm following all the Python rules: I've put "self"
> before "forename" to make sure it's treated as a data attribute
> (instance variable.) And from within a class, I'm told, you need to
> prefix the var with self too. RandomName is a class that I've tested
> (and which still works.)

Doesn't look like you've executed RandomName() in this particular
example.


> So why do I get this error?
>
>   File "h:\Testing\NameDb\dictfile.py", line 107, in randomName
>     return {"Forename" : self.forename.randomByWeight(),
> AttributeError: RandomPerson instance has no attribute 'forename'

Next time, show the *full* traceback.

>
> Here's the code (Python 2.6, PythonWin):
>
> class RandomPerson:
>     def __init(self):

Because you named this method __init instead of __init__

Next time, before proclaiming innocence, insert a print statement or
two:
           print "Hello from RandomPerson.__init"
and wonder what the problem is if the print statement is not executed
>         self.forename = RandomName("h:\\Testing\\NameDb\
> \Forenames.csv", namefield = "Forename")
>         self.surname = RandomName("h:\\Testing\\NameDb\\Surnames.csv",
> namefield = "Surname")
>         self.randomAddress = dictfile("h:\\Testing\\NameDb\
> \Addresses.csv").cycleShuffled()
> [...]
>
>     def randomName(self):
>         return {"Forename" : self.forename.randomByWeight(),
>                 "Surname" : self.surname.randomByWeight()}
>
> if __name__ == "__main__":
>     person = RandomPerson()

and here's another good place for a print statement:
      print person.__dict__

>     print person.randomName()

Cheers,
John



More information about the Python-list mailing list