我最近在 python 中發現了函式屬性。在閉包和嵌套函式中使用這些屬性是否是一種好習慣,尤其是從內部函式中更改這些屬性?它比使用“更好”nonlocal嗎?
例如-
def combination_lock(*args):
combination_lock.index = 0
code = [*args]
combination_lock.state = True
def inner(num):
if code[combination_lock.index] != num:
combination_lock.state = False
if combination_lock.index == len(code) - 1:
return combination_lock.state
else:
combination_lock.index = 1
return inner
return inner
f=combination_lock(1,2,3,4)
f(1)(2)(3)(4) # -> will return True
f(2)(1)(3)(4) # -> will return False
f(1)(1)(1)(1) # -> will return False
該函式combination_lock接收整數序列,并回傳一個函式,該函式一次獲取一個整數(整數數量與序列長度完全相同),并檢查它們是否與初始序列匹配。
如您所見,我使用了一個布爾標志來指示當前 int 是否與序列匹配,并使用索引屬性來增加對內部函式的每次呼叫。
有沒有更 Pythonic 的方式來做到這一點?
uj5u.com熱心網友回復:
簡而言之,答案是否定的,使用函式屬性不是 Pythonic,除非它們是在整個程式中不會改變的常量,例如數學常量或錯誤代碼或檔案。
主要問題是您的內部函式回傳一個函式或一個布林值......這非常令人困惑并且會導致錯誤
f=combination_lock(1,2,3,4)
f(1)(2)(3)(4) # -> will return True
f(2)(1)(3)(4) # -> will raise error because (2) returns bool
f(1)(1)(1)(1) # -> will raise error because (1) returns bool
第二個問題主要是記憶體,因為你combination_lock.index在所有創建的實體之間共享f,這使得除錯甚至正常作業都變得困難,這就是為什么不建議使用函式屬性的原因,除非它們是常量。
您嘗試使用函式屬性實作的是存盤資料,而這正是類的用途,您可以多載__call__運算子以像函式一樣作業。
為了分離內部狀態,index您state可以創建一個內部類來跟蹤它們,當您呼叫主類時將回傳該內部類,其他類將處理后續呼叫。
class combination_lock: # class to hold the code
class evaluator: # inner class to hold index and state
def __init__(self,code):
self.code = code
self.index = 0
self.state = True
# will be called every successive time after the first.
def __call__(self, num):
if self.code[self.index] != num:
self.state = False
if self.index == len(self.code) - 1:
return self.state
else:
self.index = 1
return self
def __init__(self,*args):
self.code = [*args]
def __call__(self,num): # will be called only the first time
evaluator = self.evaluator(self.code)
return evaluator(num)
f=combination_lock(1,2,3,4)
print(f(1)(2)(3)(4)) # -> will print True
print(f(2)(1)(3)(4)) # -> will print False
print(f(1)(1)(1)(1)) # -> will print False
它比你的代碼要多得多,但它更清晰和可除錯,并且可以說是 pythonic,但它仍然容易出錯,我會為其添加大量錯誤處理,但至少它現在是執行緒安全的,所以你可以創建很多任何執行緒上的組??合鎖,您將確保它們都按預期作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/412376.html
標籤:
上一篇:如何創建一個從物件中省略鍵/值對的函式,并創建一個具有剩余屬性和值的新物件?
下一篇:堆排序,關于涉及范圍的方法的實作
