开发者

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: '开发者_Go百科, 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?


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()


sess [i % 3].here

does nothing. You want to call it:

sess[i % 3].here()


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜