2011-08-02 26 views
0

已将Abc类实例存储为以数字为关键字的字典值。然后我想使用dict键找到一个实例并为该实例调用“here”函数。代码(在MS运7的Python 3.2):作为方法调用的类实例的字典值

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

产生以下输出:

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没有被用于任何实例执行。这是可行的吗?如果是的话,我需要什么代码?

回答

1
sess [i % 3].here 

什么都不做。你想叫它:

sess[i % 3].here() 
2

你是个红宝石吗?在蟒蛇括号总是强制性的调用方法:

sees [i % 3].here 

必须

sees[i % 3].here() 
0

不缩进的here()__init__定义 - 它应该是在同一水平__init__

您还需要实际调用该函数 - 在sees [i % 3].here之后添加()

+0

格式缩排(?) - 我没有原始代码。这里()工作。 – steve

+0

好的。然后我将它固定在你的文章中。 – Amber