indexed property? Can it be done?

Peter Otten __peter__ at web.de
Tue May 8 03:50:13 EDT 2012


Charles Hixson wrote:

> class Node:
> 
>      def    __init__(self, nodeId, key, value, downRight, downLeft,
>      parent):
>          dirty    =    True
>          dlu    =    utcnow()
>          self.node    =    [nodeId, downLeft, [key], [value],
> [downRight], parent, dirty, dlu]
> 
> Note that node[3] is a list of keys (initially 1) and node[3] is a list
> of values, etc.
> 
> What I'd like to do is to be able to address them thusly:
> k = node.key[2]
> v = node.value[2]
> but if there's a way to do this, I haven't been able to figure it out.
> Any suggestions?

I don't see the problem: 

>>> class Node(object):
...     def __init__(self, key):
...             self.node = ["foo", "bar", [key], "baz"]
...     @property
...     def key(self):
...             return self.node[2]
... 
>>> node = Node(42)
>>> node.key
[42]
>>> node.key[0]
42
>>> node.key.append(7)
>>> node.key
[42, 7]
>>> del node.key[0]
>>> node.key[:] = [3, 2, 1]
>>> node.key
[3, 2, 1]
>>> node.key = "foo"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

But the design proposed by Dan Sommers really is the way to go...




More information about the Python-list mailing list