property collections
Robin Becker
robin at jessikat.fsnet.co.uk
Mon May 21 07:29:56 EDT 2001
In article <20010520.122427.352118606.1074 at bur-jud-
175-197.rh.uchicago.edu>, Ben Wolfson <wolfson at uchicago.edu> writes
>In article <g44pZKATy8B7Ewa2 at jessikat.fsnet.co.uk>, "Robin Becker"
><robin at jessikat.fsnet.co.uk> wrote:
...
well I tried and get an error
C:\Python\reportlab\graphics>python \tmp\tpc.py
TPC a=1001 b=1002
Traceback (most recent call last):
File "\tmp\tpc.py", line 34, in ?
print 'TPC[%d] a=%d b=%d'% (i, TPC[i].a, TPC[i].b)
AttributeError: 'Properties' instance has no attribute 'b'
################# yoir code + __len__ method and test
class PropertyCollection:
class Properties:
def __init__(self, dict):
self.__dict__.update(dict)
def __init__(self):
self.__dict__['attrs'] = {}
self.__dict__['i_attrs'] = {}
def __getitem__(self, i):
if not self.i_attrs.has_key(i):
self.i_attrs[i] = self.Properties(self.attrs)
return self.i_attrs[i]
def __getattr__(self, k):
return self.attrs[k]
def __setattr__(self, k, v):
self.attrs[k] = v
def __delattr__(self, k):
del self.attrs[k]
def __len__(self):
return len(self.i_attrs)
TPC = PropertyCollection()
TPC[0].a=11
TPC.a = 31
TPC[1].b=12
TPC.b = 32
TPC[2].a=101
TPC.a=1001
TPC.b =1002
n=len(TPC)
print 'TPC a=%d b=%d'% (TPC.a, TPC.b)
for i in xrange(n):
print 'TPC[%d] a=%d b=%d'% (i, TPC[i].a, TPC[i].b)
--
Robin Becker
More information about the Python-list
mailing list