Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 796
Azeirah Avatar asked Oct 17 '13 21:10

Azeirah


People also ask

How do you assign a variable to a function?

Method 1: Assign Function Object to New Variable Name A simple way to accomplish the task is to create a new variable name g and assign the function object f to the new variable with the statement f = g.

Can you assign a variable within a function?

You can assign global variables from inside the function using "<<-" operator.

How do you assign variables in Python?

In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign ( = ).


1 Answers

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
like image 166
RichieHindle Avatar answered Sep 22 '22 20:09

RichieHindle