[英]Assigning a variable directly to a function in Python
請考慮以下代碼:
def apples():
print(apples.applecount)
apples.applecount += 1
apples.applecount = 0
apples()
>>> 0
apples()
>>> 1
# etc
這是一個好主意,壞主意還是我應該摧毀自己? 如果你想知道為什么我會想要這個,我有一個函數每4秒重復一次,使用win32com.client.Dispatch()
它使用windows COM連接到一個應用程序。 我認為沒有必要每4秒重新創建一次鏈接。 我當然可以使用全局變量,但我想知道這是否也是一個有效的方法。
使用類的實例變量來保持計數會更加慣用:
class Apples:
def __init__(self):
self._applecount = 0
def apples(self):
print(self._applecount)
self._applecount += 1
a = Apples()
a.apples() # prints 0
a.apples() # prints 1
如果您需要引用只是函數本身,沒有a
參考,你可以這樣做:
a = Apples()
apples = a.apples
apples() # prints 0
apples() # prints 1
它基本上是一個命名空間全局。 您的函數apples()
是一個全局對象,該對象上的屬性也不亞於全局。
它僅略微優於常規全局變量; 畢竟,命名空間一般都是個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.