Class static variables
Guillaume
forums at memoire.com
Mon Jul 24 05:15:05 EDT 2000
Axel understood perfectly the goal of my question and the way I would
like the code to behave.
> This alteration is actually easier for the class case, as has
> been pointed out, as long as, of course, __setattr__ knows
> about it. For the variable case you'd HAVE to say global in
> each block that rebinds it (analogous to saying CA.a in an
> explicit way for the class field case, I guess).
So here is the code which seams to do what I want. The few tests I made
give good results. The only problem is the need to modify __setattr__
but it is not a problem for generated code (Java,C++,... -> Python)
The only problem will be for Python->Python... but first my tool doesn't
have a Python parser yet and second, I could mark special cases. Of
course the fact to change the semantic of attributes can be a problem if
someone want to maintain the generated code.
First I used constructs like if name=="x": but in fact the use of try:
makes it more general (no need to know the attribute name). Inheritance
seams to work.
If you know a better way, tell me.
Guillaume
This code will be released in Alma 0.26
http://www.memoire.com/guillaume-desnoix/alma/
#### CODE ####
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