繁体   English   中英

如何通过字典键值对中的参数传递函数

[英]How to pass function with parameters in a dictionary key value pair

我是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)

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

试试这个代码:

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

它可以满足您的需求。

这样做的方式是,函数将被调用并存储结果(由于没有返回任何内容,因此将其存储为None),如果您希望像这样调用该函数,则可以在其周围编写一个lambda或使用functools.partial

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM