__peter__ at web.de
Wed Nov 19 10:52:57 CET 2003
John Hunter wrote:
> I have some (potentially mutable) scalar values that I want to share
> among many class instances. Changes in one instance should be
> reflected across the many instances. A classic Borg is not
> appropriate because I have more than one instance.
Below is a slight variation of your approach. I think both the beauty and
the danger is that, for read access, attributes defined in the client
instance are indistinguishable from attributes defined in the template
object. I've separated them here, but you could even use a UseTemplate
instance as the template for another instance.
def __init__(self, **kwd):
german = Template(color="blue", language="german")
french = Template(color="yellow", language="french")
def __init__(self, name, template=german):
self.name = name
self.template = template
def __getattr__(self, name):
"Attributes not found in UseTemplate are looked up in the template"
return getattr(self.template, name)
print "name=%s, color=%s, language=%s" % (u.name, u.color, u.language)
first = UseTemplate("first", german)
second = UseTemplate("second", french)
special = UseTemplate("special", french)
for u in [first, second, special]:
# instance attributes shade template attributes
special.color = "black"
# changes in template affect all instances using it
french.color = "red"
del special.color # the template attr will reappear
More information about the Python-list