【发布时间】:2011-08-02 06:15:16
【问题描述】:
已将 Abc 类实例存储为以数字为键的 dict 值。然后我想使用 dict 键来查找一个实例并为该实例调用函数'here'。 (MS Win 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 没有针对任何实例执行。这是可行的吗?如果是这样,我需要什么代码?
【问题讨论】:
标签: python class function dictionary