I am new to python and was trying to create a dictionary with value as a function. here is my code
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) }
doesn't store the functions as the values in the dictionary.
It calls the functions print1
and print2
and stores their return values. Since both the functions only print
and don't return anything, you get the dictionary {'a': None, 'b': None }
which is why you are getting the NoneType
exception.
Instead, you should do:
bar = {'a': self.print1, 'b': self.print2 }
Then:
bar['b'](5)
>> 5
Try this code:
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()
It does what you want.
这样做的方式是,函数将被调用并存储结果(由于没有返回任何内容,因此将其存储为None),如果您希望像这样调用该函数,则可以在其周围编写一个lambda
或使用functools.partial
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.