Global variables within classes.

B

Bruno Desthuilliers

Kevac Marko a écrit :
When changing default value, is there any way to change class
attribute and all referenced attributes too?

class M:
name = u"Marko"

a, b = M(), M()
a.name = u"Kevac"
print M.name, a.name, b.name
-> Marko Kevac Marko

Is there any way to get here -> Kevac Kevac Kevac ?

class ClassAttribute(object):
"""
If you dont understand this code, google for
+python +descriptor +protocol
"""
def __init__(self, attrname, default=""):
self.attrname = attrname
self.default = default

def __get__(self, inst, cls):
return getattr(cls, self.attrname, self.default)

def __set__(self, inst, val):
setattr(type(inst), self.attrname, val)

class M(object):
name = ClassAttribute('_name', "Marko")

a, b = M(), M()
a.name = u"Kevac"
print M.name, a.name, b.name

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top