static variables
Ulli Horlacher
framstag at rus.uni-stuttgart.de
Tue Dec 1 06:47:59 EST 2015
Wolfgang Maier <wolfgang.maier at biologie.uni-freiburg.de> wrote:
> I'm wondering whether you have a good reason to stick with a function.
Easy handling, no programming overhead. Clean, orthogonal code.
> What you are trying to achieve seems to be easier and cleaner to
> implement as a class:
>
> class Counter (object):
> def __init__ (self, start_value=0):
> self.x = start_value
>
> def __call__ (self):
> self.x += 1
>
> 1) solves the renaming problem
> 2) allows you to have several counters around:
>
> counter1 = Counter()
> counter2 = Counter()
> counter3 = Counter(35)
> counter1()
> counter2()
> counter1()
> print (counter1.x, counter2.x, counter3.x)
Implementing a counter was only an example for a static variable, not the
primary goal.
With a class, I find it irritating the first function call have to be
different than the subsequent ones:
def main():
a=A(1)
a(1)
a(5)
a(0)
print(a.n)
class A(object):
def __init__ (self,*arg):
self.n = 0
def __call__(self,x):
self.n += 1
print('%d:' % self.n,x)
main()
--
Ullrich Horlacher Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de
Universitaet Stuttgart Tel: ++49-711-68565868
Allmandring 30a Fax: ++49-711-682357
70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/
More information about the Python-list
mailing list