【问题标题】:Assigning a variable directly to a function in Python将变量直接分配给Python中的函数
【发布时间】:2013-10-17 21:25:49
【问题描述】:

考虑以下代码:

def apples():
    print(apples.applecount)
    apples.applecount += 1

apples.applecount = 0
apples()
>>> 0
apples()
>>> 1
# etc

这是一个好主意,坏主意还是我应该摧毁自己? 如果你想知道我为什么想要这个,我有一个函数每 4 秒重复一次,使用 win32com.client.Dispatch() 它使用 windows COM 连接到应用程序。我认为没有必要每 4 秒重新创建一次该链接。 我当然可以使用全局变量,但我想知道这是否也是一种有效的方法。

【问题讨论】:

    标签: python function variables


    【解决方案1】:

    使用类的实例变量来保持计数会更惯用:

    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
    

    【讨论】:

    • 很好的建议。基本上,当你想把状态(以显式变量的形式)和功能放在一起时,你想要的通常是一个类。
    【解决方案2】:

    它基本上是一个命名空间的全局。您的函数apples() 是一个全局对象,该对象上的属性同样具有全局性。

    它只比普通的全局变量稍微好一点;毕竟,命名空间通常是个好主意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 2023-03-22
      相关资源
      最近更新 更多