【问题标题】:Dict value as Class instance for method call字典值作为方法调用的类实例
【发布时间】: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


    【解决方案1】:

    你是红宝石爱好者吗?在 python 中,括号总是强制调用方法:

    sees [i % 3].here
    

    必须是

    sees[i % 3].here()
    

    【讨论】:

      【解决方案2】:
      sess [i % 3].here
      

      什么都不做。你想叫它:

      sess[i % 3].here()
      

      【讨论】:

        【解决方案3】:

        不要在__init__ 下缩进here() 的定义 - 它应该与__init__ 处于同一级别。

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

        【讨论】:

        • 由于格式化而缩进(?) - 我在原始代码中没有它。这里()起作用了。
        • 好的。然后我在你的帖子中修复了它。
        猜你喜欢
        • 2010-10-26
        • 1970-01-01
        • 1970-01-01
        • 2010-10-23
        • 1970-01-01
        • 2013-01-09
        • 1970-01-01
        • 2017-02-05
        • 2019-03-03
        相关资源
        最近更新 更多