Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Python __getitem__ AttributeError

Name: Anonymous 2010-08-29 21:47

I don't normally work with python, but noodling around with it has been fairly easy until I hit this brickwall:

so I make a class, lets say "person". now I make a whole bunch of instances of person. I take each person, and make them as a value inside a dictionary, "people" keyed to zero through n, where n is the number of persons.

Then I put this dictionary inside a new class, lets call it city, so that in any instance of a city I can have this dictionary of persons, with their individual keys.

I made an instance of this hypothetical city class, and tried to call one of these persons through their key, ie exampleCity.people[i], were i is the key, and python spits out at me "instance has no attribute '__getitem__'"

I'm trying to have a for loop run through the city's dictionary of people, but no matter how I try to swing it, python keeps throwing this AttributeError

do I need to define some sort of get and set functions? I thought python keeps attributes as public by default...

Name: Anonymous 2010-08-29 21:50

This is boring. Troll harder.

Name: Anonymous 2010-08-29 21:51

You need to provide some code, a description isn't enough because you're most likely doing something else. Don't forget the [code] tags when posting code!

Name: Anonymous 2010-08-29 21:58

>>3
I would rather the OP post the code on pastebin rather than shitting up /prague/

Name: Anonymous 2010-08-29 22:27

wow... actually I figured it out on my own. The example I gave was an oversimplification of a different problem, using people and city as an arbitrary analogy, but in trying to code the simplification, I found my answer


class Person:
    def __init__(self, name):
        self.name = name

class City:
    def __init__(self, name, size):
        self.name = name
        self.size = size
        self.people = {}
        for n in range(0,size):
            self.people[n] = Person("nobody_special")

exampleCity = City("Exampleville", 10)
print exampleCity.people[5].name



I think my problem was in line 11, in originally not putting a "self." before people[n].
still trying to replicate the AttributeError report, but I think I understand it slightly better, or at least have proven to myself that it is possible.

Name: Anonymous 2010-08-29 23:06

>>5
Of, all fine now? Fuck off then.

Name: Anonymous 2011-02-04 19:27


Don't change these.
Name: Email:
Entire Thread Thread List