indexed property? Can it be done?
Charles Hixson
charleshixsn at earthlink.net
Tue May 8 00:18:37 EDT 2012
On 05/07/2012 08:44 PM, Dan Sommers wrote:
> On Mon, 07 May 2012 20:15:36 -0700
> Charles Hixson<charleshixsn at earthlink.net> 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?
>>
> Untested:
>
> def __init__(self, nodeId, key, value, downRight, downLeft, parent):
> dirty = True
> dlu = utcnow()
> self.node = [nodeId, downLeft, dict(key=value),
> [downRight], parent, dirty, dlu]
>
> Now you can use self.node[2][key] to get/set value.
>
> But why not make the elements of node their own attributes?
>
> Untested:
>
> def __init__(self, nodeId, key, value, downRight, downLeft, parent):
> self.dirty = True
> self.dlu = utcnow()
> self.nodeId = nodeId
> self.downLeft = downLeft
> self.downRight = downRight
> self.values = dict(key=value)
> self.parent = parent
>
> And then you don't have to remember that node[2] is the key/value pairs
> (note the typo (the two "3"s) in your original post). With each
> attribute in its own, well, attribute, you can always use
> node.values[key] to access the value associated with a particular key.
>
> HTH,
> Dan
>
Did you notice that the node list contained sublists? I can access the
top level node items through ordinary properties, and that is my
intent. So I don't need to remember what top level index represents
what item. But the second level items are variable in length, so I
really want to do an indexed access to them.
Yes, I admit that in the snipped defined by the __init__ method those
secondary lists only received one entry. Other method would extend
their length, to a variable amount for different class instances.
A part of the reason that the class retains that top level list is so
that if I can't create an indexed property to get and set them, I can
revert to an alternative that is a bit uglier than this, but might be
more efficient. (It would have methods that operated directly on the
list rather than using properties for ANY of the approach...and avoid
creating a class that they handle. Not as clean as what I'm hoping for,
but so far I haven't come up with any way except functions that doesn't
directly expose the data...and if I must use that approach, then the
class doesn't buy me anything for the overhead.)
--
Charles Hixson
More information about the Python-list
mailing list