scalar references

Peter Otten __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.

class Template:
    def __init__(self, **kwd):
        self.__dict__.update(kwd)


german = Template(color="blue", language="german")
french = Template(color="yellow", language="french")

class UseTemplate:
    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)

def printit(u):
    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)

def printThem():
    for u in [first, second, special]:
        printit(u)
    print

printThem()

# instance attributes shade template attributes
special.color = "black"

# changes in template affect all instances using it
french.color = "red"

printThem()

del special.color # the template attr will reappear
printThem()

Peter




More information about the Python-list mailing list