Use list name as string
Jervis Whitley
jervisau at gmail.com
Wed Feb 4 22:53:28 EST 2009
On Thu, Feb 5, 2009 at 2:37 PM, Vincent Davis <vincent at vincentdavis.net> wrote:
> Jervis Whitley wrote "Although you should really solve your problem by
> thinking about it
> from a completely different angle, maybe subclassing your datatype and
> adding a 'name'
> attribute ? I'm sure some of the others here have suggested that already."
> That is beyond my current knowledge. Any suggestions for reading about this?
> Thanks
> Vincent Davis
Here is a short example, more information on 'Inheritance' can be obtained from
http://docs.python.org/tutorial/classes.html
class NamedList(list):
"""A List with a 'name' attribute."""
def __init__(self, name, *args, **keyword_arguments):
list.__init__(self, *args, **keyword_arguments)
self.name = name
you can now do this
x = NamedList('x', [1,2,3,4])
>>> x.name
'x'
In this example I have inherited all the features of the original
built-in list, and added my
own initialisation method.
of course this is only a minimal example and there are other
approaches (such as adding an attribute
at runtime) but this one
is self documenting to some extent.
Cheers,
More information about the Python-list
mailing list