steve
steve

Reputation: 1

Dict value as Class instance for method call

Have stored Abc class instances as dict values with a number as the key. I then want to use the dict key to find an instance and call the function 'here' for that instance. The (Python 3.2 on MS Win 7) code:

class Abc():

    def __init__ ( self, num ):
        self.num = num
        print ( 'Starting sess no - ', self.num )

    def here ( self ):
        print ( 'Here - ', self.num )

def main():
    sess = dict ((i, Abc(i)) for i in range ( 3 ))
    for i in range ( 7 ):
        print ('Go to Sess - key: ', i % 3, ' value: ', sess [i % 3] )
        try:
            sess [i % 3].here
        except:
            raise KeyError ('Problem with key')

which produces this output:

Starting sess no -  0

Starting sess no -  1

Starting sess no -  2

Go to Sess - key:  0  value:  <__main__.Abc object at 0x00C193B0>

Go to Sess - key:  1  value:  <__main__.Abc object at 0x00C19510>

Go to Sess - key:  2  value:  <__main__.Abc object at 0x00C19530>

Go to Sess - key:  0  value:  <__main__.Abc object at 0x00C193B0>

Go to Sess - key:  1  value:  <__main__.Abc object at 0x00C19510>

Go to Sess - key:  2  value:  <__main__.Abc object at 0x00C19530>

Go to Sess - key:  0  value:  <__main__.Abc object at 0x00C193B0>

Abc.here is not being executed for any instance. Is this doable? If so what code do I need?

Upvotes: 0

Views: 1627

Answers (3)

Amber
Amber

Reputation: 527548

Don't indent the definition of here() underneath __init__ - it should be at the same level as __init__.

You also need to actually call the function - add () after sees [i % 3].here.

Upvotes: 0

GaretJax
GaretJax

Reputation: 7780

Are you a rubyist? In python parentheses are always mandatory to call a method:

sees [i % 3].here

has to be

sees[i % 3].here()

Upvotes: 2

phihag
phihag

Reputation: 288298

sess [i % 3].here

does nothing. You want to call it:

sess[i % 3].here()

Upvotes: 1

Related Questions