我对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)
通过这种方式,函数被调用,结果被存储(这是None,因为您不返回任何东西),如果您希望函数可以这样调用,您可以在它周围写一个
lambda
或者使用functools.partial
请尝试以下代码:
它做你想做的。在
bar = {'a': self.print1(6), 'b': self.print2(5) }
不将函数作为值存储在字典中。在它调用函数
print1
和print2
,并存储它们的返回值。因为这两个函数都只print
,并且不返回任何内容,所以得到了字典{'a': None, 'b': None }
,这就是为什么得到NoneType
异常的原因。在相反,您应该:
bar = {'a': self.print1, 'b': self.print2 }
然后:
相关问题 更多 >
编程相关推荐