简体   繁体   中英

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. I think it's unnecessary to recreate that link every 4 seconds. 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 = 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.

It is only marginally better than a regular global variable; namespaces in general are a good idea, after all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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