how to define a static field of a given class
Maric Michaud
maric at aristote.info
Fri Jun 2 05:26:13 EDT 2006
Le Vendredi 02 Juin 2006 11:07, feel_energetic a écrit :
> Hi,
>
> I already knew how to define a static method of a class( using
> staticmethod() ),but I find there isn't a built-in func to build a
> static field ( something like staticfield() )
> can anyone help me on this?
> thanks very much for your help :)
I guess you come from a c++ background, and what you mean by static field is a
variable shared by all instance of the class, right ?
then,
class toto :
VAL=5
but, you can't assign directly via instances of the class as it will override
VAL in the instance :
In [2]: t=toto()
In [3]: t.VAL=4
In [4]: toto.VAL
Out[4]: 5
In [5]: t.__dict__
Out[5]: {'VAL': 4}
You must explicitly modify t.__class__.VAL or toto.VAL :
In [8]: t1, t2 = toto(), toto()
In [9]: t1.__class__.VAL = 4
In [10]: t2.VAL
Out[10]: 4
--
_____________
Maric Michaud
_____________
Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
More information about the Python-list
mailing list