On 01.12.2015 09:26, Ulli Horlacher wrote:
Steven D'Aprano <st...@pearwood.info> wrote:
A better and more general test is:
if hasattr(a, 'x'): print('attribute of a')
Fine!
I have now:
def a(x=None):
if not hasattr(a,'x'): a.x = 0
a.x += 1
print('%d:' % a.x,x)
This simply counts the calls of a()
But, when I rename the function I have to rename the attribute also.
Is it possible to refer the attribute automatically to its function?
Something like:
def a(x=None):
if not hasattr(_function_,'x'): _function_.x = 0
_function_.x += 1
print('%d:' % _function_.x,x)
I'm wondering whether you have a good reason to stick with a function.
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)
Cheers,
Wolfgang
--
https://mail.python.org/mailman/listinfo/python-list