Class static variables
Guillaume
forums at memoire.com
Fri Jul 21 12:56:12 EDT 2000
> > I'm writing a tool to translate a variety of OO
> > programming languages. Especially I target Python
> > but I am hesitating about the way to define
> > class-scope static variables. Could you suggest me
> > what is the best and natural form ?
> >
> > Example: MyClass { static int a; }
> > - MyClass_a
> > - accessors + global var
> > - any other form
> MyClass.a will work unless it is a function. (class attributes that
are
> functions are magically turned into instance methods) For example:
>
> class MyClass:
> #define class attribute
> a = 0
> def method(self):
> #use class attribute
> do_something_with(MyClass.a)
>
> #use class attribute outside of MyClass
> do_something_else_with(MyClass.a)
Thanx for the answer but...
>>> class CA:
... a=0
...
>>> b=CA()
>>> b.a
0
>>> b.a=2
>>> c=CA()
>>> c.a
0
>>> b.a
2
# c.a should be 2 and not 0 if a is a static attribute.
>>> class CB(CA):
... pass
>>> CB.a=3
>>> CB.a
3
>>> CA.a
0
# here a big problem. the attribute is not inherited...
So for all these reasons, I think I will use __getattr__ and __setattr__
Here is the code I should generate for managing static vars.
Fortunately, there is no need to change the python access for reading.
class A:
def __setattr__(self,name,value):
print "A: set "+name+" %s" % value
try:
A.__dict__[name]
A.__dict__[name]=value
return None
except KeyError:
self.__dict__[name]=value
# static vars for A
A.x="XX"
A.w="WW"
class B(A):
# instance vars for B
z=None
def __setattr__(self,name,value):
print "B: set "+name+" %s" % value
try:
B.__dict__[name]
B.__dict__[name]=value
return None
except KeyError:
A.__setattr__(self,name,value)
# static vars for B
B.y="YY"
a=A()
b=B()
b.z="ZZ"
print b.z
print b.w
print a.x
a.x="XXXX"
print a.x
print b.y
b.y="YYYY"
print b.y
print b.x
try:
print b.v
except AttributeError:
print "v is not defined..."
Sent via Deja.com http://www.deja.com/
Before you buy.
More information about the Python-list
mailing list