I'm trying to implement a so-called static variable in my method, similar to the decorator method described in this Stackoverflow thread. Specifically, I define a decorator function as follows:
def static_var(varName, value):
def decorate(function):
setattr(function,varName,value)
return function
return decorate
As the example shows, this can be used to attach a variable to the function:
@static_var('seed', 0)
def counter():
counter.seed +=1
return counter.seed
This method will return the number of times it has been called.
The issue i am having is that this does not work if I define the method inside a class:
class Circle(object):
@static_var('seed',0)
def counter(self):
counter.seed +=1
return counter.seed
If I instantiate a Circle
and run counter
,
>>>> myCircle = Circle()
>>>> myCircle.counter()
I get the following error: NameError: global name 'counter' is not defined
.
My response to this was that maybe I need to use self.counter
, i.e.
class Circle(object):
@static_var('seed',0)
def counter(self):
self.counter.seed +=1
return self.counter.seed
However this produces the error, AttributeError: 'instancemethod' object has no attribute 'seed'
.
What is going on here?