(newbie) Is there a way to prevent "name redundancy" in OOP ?
"Martin v. Löwis"
martin at v.loewis.de
Sun Jan 7 19:16:40 EST 2007
Stef Mientki schrieb:
> Can this be achieved without redundancy ?
You can use the registry design to use the object's name also to find
the object. In the most simple way, this is
registry = {}
class pin:
def __init__(self, name):
registry[name] = self
self.name = name
pin('aap')
print registry['aap']
Using computed attribute names, you can reduce typing on attribute
access:
class Registry: pass
registry = Registry()
class pin:
def __init__(self, name):
setattr(registry, name, self)
self.name = name
pin('aap')
print registry.aap
If you want to, you can combine this with the factory/singleton
patterns, to transparently create the objects on first access:
class Registry:
def __getitem__(self, name):
# only invoked when attribute is not set
r = pin(name)
setattr(self, name, r)
return r
registry = Registry()
class pin:
def __init__(self, name):
self.name = name
print registry.aap
HTH,
Martin
More information about the Python-list
mailing list