我想了解函式表中調度表的設計。
這是我最初編碼的內容
class Aave():
def __init__(self,address):
self.address = address
def function_map(self):
mapping = {1:self.test(),2:self.test2()}
print(type(self.test()))
return mapping[self.address]()
def test(self):
print(1)
return 1
def test2(self):
print(2)
return 2
a = Aave(1)
print(a.function_map())
但是,此函式將呼叫 2 函式self.test()
,self.test2()
而不僅僅是與 key 關聯的函式self.test()
。
另一方面,編碼不帶括號的調度表將執行指定的映射函式
像這樣
def function_map(self):
mapping = {1:self.test,2:self.test2}
print(type(self.test()))
return mapping[self.address]()
我已經提到了試圖理解的不同資源,但它們并沒有解釋行為上的差異。
我想知道是否有人可以就這個問題提供一些啟示。
參考:
https://www.oreilly.com/library/view/python-cookbook/0596001673/ch01s07.html
https://betterprogramming.pub/dispatch-tables-in-python-d37bcc443b0b
uj5u.com熱心網友回復:
為了理解這個問題,讓我們像解釋器一樣逐行閱讀代碼:
# First of all object creation is executed
a = Aave(1)
# This invokes method __init__ of class Aave, hence next step is
a.address = 1
# After the creation of a class instance, interpreter tries to run
print(a.function_map())
# But since value of a.function_map() is unknown it needs to be calculated first
# Hence, interpreter enters function_map method of class Aave
# Execution of
mapping = {1:self.test(), 2:self.test2()}
# requires the test() and test2() to be evaluated. Since brackets indicate function call
# Thus, test() runs, prints 1 and returns 1. If we could see the value of
# mapping after this, it would have been:
# {1: 1, 2: <unknown yet result of self.test2()>}
# ^
# This value is the result of self.test()
# Next self.test2() is evaluated, since it also has brackets and needs to be called
# test2() runs, prints 2 and returns 2.
# After this step, mapping looks like {1: 1, 2: 2}
# ^ ^
# Had this already result of self.test2()
# After this mapping is completely known and next line may be evaluated.
# Evaluating
print(type(self.test()))
# causes one more call to self.test,
# since it also has brackets.
# And when you finally evaluate last line
return mapping[self.address]()
# Keeping in mind, that mapping was {1: 1, 2: 2}, you try to take value by key 1 from mapping,
# which is 1 (int). And call it (since you put "()"). It causes error, because 1 int is not callable.
因此,您有 2 個呼叫self.test()
in 行
mapping = {1:self.test(), 2:self.test2()}
# AND
print(type(self.test()))
和一個呼叫self.test2()
排隊
mapping = {1:self.test(), 2:self.test2()}
如果您希望能夠呼叫存盤在 中的內容mapping
,則需要在mapping
創建時洗掉這些括號。通過這種方式,您可以將函式物件存盤在 dict 而不是函式結果中。
mapping = {1:self.test(), 2:self.test2()} # Call functions and store results
# VS
mapping = {1:self.test, 2:self.test2} # Store functions themselves
這是整個區別。帶括號 - 函式呼叫的結果,不帶 - 函式物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/322844.html
上一篇:轉換字典串列中的字串
下一篇:找出兩個圖形之間的差異