static variables
Terry Reedy
tjreedy at udel.edu
Mon Nov 30 12:38:40 EST 2015
On 11/30/2015 12:15 PM, Ulli Horlacher wrote:
>
> I try to to implement a "static variable" inside a function:
>
> def main():
> a(1)
> a(2)
> a()
> print(a.x)
> if 'a.x' in globals(): print('global variable')
> if 'a.x' in locals(): print('local variable')
>
> def a(x=None):
> if not x is None: a.x = x
> print(':',a.x)
>
> main()
>
> When I run this code, I get:
>
> : 1
> : 2
> : 2
> 2
>
> This is exactly what I expect.
> But what is a.x?
> It is neither a variable in globals() nor in locals()
a.x is an attribute of the object a.
--
Terry Jan Reedy
More information about the Python-list
mailing list