0

Here's the faulty bit of my code:

class Room(object):
    def __init__(self):
        self.hotspots = []
        self.image = []
        self.item = []

    def newhotspot(*args):
        new = {'Name' : None,
               'id' : None,
               'rect' : None,
               'Takeable' : None,
               'Lookable' : None,
               'Speakable' : None,
               'Itemable' : None,
               'Goable' : None}

        for i in args:
            new[i[0]] = i[1]
        new['id'] = len(self.hotspots)
        self.hotspots.append(new)

CityTrader = Room()

CityTrader.newhotspot(('Name', 'Trader'),
                      ('Takeable', 'Yes'))

The goal is to have a dictionary with all the keys set to none but the ones specified. However, when I run it I get:

[...]line 85 in <module>
('Takeable', 'Yes'))
[...]line 44, in newhotspot
new[i[0]] = i[1]
TypeError : 'Room' object does not support indexing

Anyone knows why and how to solve this? It seems to work when it's not wrapped inside a class.

2 Answers 2

6

You forgot the self parameter to newhotspot():

def newhotspot(self, *args):
    ...

Since self will be implicitly passed anyway, it ends up as the first item of args.

Sign up to request clarification or add additional context in comments.

Comments

1

Every class method must take self as it's first argument.

Try this:

class Room(object):
    def __init__(self):
        self.hotspots = []
        self.image = []
        self.item = []

    def newhotspot(self, *args):
       new = {'Name' : None,
       'id' : None,
       'rect' : None,
       'Takeable' : None,
       'Lookable' : None,
       'Speakable' : None,
       'Itemable' : None,
       'Goable' : None}

       for i in args:
           new[i[0]] = i[1]
       new['id'] = len(self.hotspots)
       self.hotspots.append(new)

CityTrader = Room()

CityTrader.newhotspot(('Name', 'Trader'),
                      ('Takeable', 'Yes'))

1 Comment

Wrong, class methods take the class as first argument. Instance methods have self as the first parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.