Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Peter Otten <__peter__@web.de> Newsgroups: comp.lang.python Subject: Re: static variables Date: Tue, 01 Dec 2015 10:01:54 +0100 Organization: None Lines: 41 Message-ID: References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Trace: news.uni-berlin.de HuP1M4FlCmLWQ5Ecl3a+pQGUtnsJLfuNO2TVZXhadoRg== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.004 X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'rename': 0.07; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'def': 0.13; 'a()': 0.16; 'function?': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:io': 0.16; 'received:plane.gmane.org': 0.16; 'received:psf.io': 0.16; 'received:t-ipconnect.de': 0.16; 'wrote:': 0.16; 'attribute': 0.18; 'header:User-Agent:1': 0.26; 'header:X-Complaints-To:1': 0.26; 'function': 0.28; 'directly,': 0.29; 'skip:_ 10': 0.32; "d'aprano": 0.33; 'steven': 0.33; 'something': 0.35; 'but': 0.36; 'there': 0.36; 'possible': 0.36; 'to:addr:python-list': 0.36; 'subject:: ': 0.37; 'received:org': 0.37; 'test': 0.39; 'to:addr:python.org': 0.40; 'received:de': 0.40; 'called': 0.40; 'more': 0.63; 'now:': 0.72; 'counts': 0.81 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: p57bd9614.dip0.t-ipconnect.de User-Agent: KNode/4.13.3 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.20+ Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:99779 Ulli Horlacher wrote: > Steven D'Aprano 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) Not directly, but there are workarounds: def with_function(f): return functools.partial(f, f) @with_function def foo(self, x=None): if not hasattr(self, "x"): self.x = 0 self.x += 1 print("{} called {} times".format(self.__name__, self.x))