简体   繁体   English

在Python中将变量直接分配给函数

[英]Assigning a variable directly to a function in Python

Consider the following code: 请考虑以下代码:

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

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

Is this a good idea, bad idea or should I just destroy myself? 这是一个好主意,坏主意还是我应该摧毁自己? If you're wondering why I would want this, I got a function repeating itself every 4 seconds, using win32com.client.Dispatch() it uses the windows COM to connect to an application. 如果你想知道为什么我会想要这个,我有一个函数每4秒重复一次,使用win32com.client.Dispatch()它使用windows COM连接到一个应用程序。 I think it's unnecessary to recreate that link every 4 seconds. 我认为没有必要每4秒重新创建一次链接。 I could of course use a global variable, but I was wondering if this would be a valid method as well. 我当然可以使用全局变量,但我想知道这是否也是一个有效的方法。

It would be more idiomatic to use an instance variable of a class to keep the count: 使用类的实例变量来保持计数会更加惯用:

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

If you need to reference just the function itself, without the a reference, you can do this: 如果您需要引用只是函数本身,没有a参考,你可以这样做:

a = Apples()
apples = a.apples

apples()  # prints 0
apples()  # prints 1

It is basically a namespaced global. 它基本上是一个命名空间全局。 Your function apples() is a global object, and attributes on that object are no less global. 您的函数apples()是一个全局对象,该对象上的属性也不亚于全局。

It is only marginally better than a regular global variable; 它仅略微优于常规全局变量; namespaces in general are a good idea, after all. 毕竟,命名空间一般都是个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM