如何在字典键值pai中传递带参数的函数

2024-09-29 05:29:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python不熟悉,正试图创建一个以值为函数的字典。这是我的密码

import os

class Foo():
    def print1(self,n):
        print 5


    def print2(self,n):
        print 6

    def foo(self):
        bar = {'a': self.print1, 'b': self.print2}
        bar['b'](5)
        bar['a'](3)
        bar[os.environ['FOO']]()


f = Foo()
f.foo()

Traceback (most recent call last):
  File "test_dict.py", line 17, in <module>
   f.foo()
  File "test_dict.py", line 13, in foo
    bar[b]()

python test_dict.py 
6 
5  
   Traceback (most recent call last):
      File "test_dict.py", line 19, in <module>
       f.foo()
      File "test_dict.py", line 15, in foo
       bar[os.environ['FOO']]()
    TypeError: print2() takes exactly 2 arguments (1 given)

Tags: inpytestselffooosdefline
3条回答

通过这种方式,函数被调用,结果被存储(这是None,因为您不返回任何东西),如果您希望函数可以这样调用,您可以在它周围写一个lambda或者使用functools.partial

请尝试以下代码:

class Foo():
    def print1(self,n):
        print 6

    def print2(self,n):
        print n

    def foo(self):
        bar = {'a': self.print1, 'b': self.print2 }
        bar['b'](5)
        bar['a'](3)

f = Foo()
f.foo()

它做你想做的。在

bar = {'a': self.print1(6), 'b': self.print2(5) }不将函数作为值存储在字典中。在

它调用函数print1print2,并存储它们的返回值。因为这两个函数都只print,并且不返回任何内容,所以得到了字典{'a': None, 'b': None },这就是为什么得到NoneType异常的原因。在

相反,您应该:

bar = {'a': self.print1, 'b': self.print2 }

然后:

bar['b'](5)
>> 5

相关问题 更多 >