[Tutor] Static Variable in Functions

Alan Gauld alan.gauld at btinternet.com
Sun Mar 13 22:21:26 CET 2011


"Yasar Arabaci" <yasar11732 at gmail.com> wrote

> exactly like static variables in other languages (as I have used in 
> php

static in other languages usually refers to variables declared
on the memory heap rather than the stack, and therefore they
retain their value between calls. Python tends to operate at a
higher level than that and so does things in other ways.

> little bit research on that, I see that there is no static variable 
> for functions but we can make things behave like that as introduced 
> here:
>
> def egg(static={"count":0}):
>     static["count"]+=1
>     return static["count"]

Yes, you can do that, see the other post earlier today for
more on how parameters work in Python.

However, you should also look at generators and the yield keyword.
These probably provide a neater way of doing what you seem to
want...

> Author of this post says that we can use mutable variables like this 
> as static function variables. I was wondering what are mutable 
> variables and what is rationale behind them.

mutable just means modifiable.
You cannot modify a number, string or tuple for example
(you need to create new objects) but you can modify a list,
dictionary or class instance. The latter are mutable, the
former immutable. You must use an immutable object as
the key in a dictionary.

These are not Python terms they are standard computing science
terms. As such you can usually find good explanations on Wikipedia.
In general Python uses quite pure computing science concepts
and so wikipedia is a good source of background reading on
most Python concepts. (eg lambda, generator, iterator, slicing  etc)


HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list