簡體   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