Newbie question about nested lists and constructor functions...
Chris Gonnerman
chris.gonnerman at usa.net
Sun Mar 4 23:01:54 EST 2001
Could you please post example(s) so we know exactly what is giving you
trouble? I at least don't quite know what you are asking.
The constructor function (Python calls it "__init__") is created thus:
class Spam:
def __init__(self):
...
and of course __init__ might have additional arguments. If you are creating
a nested list with known initializers, you might say:
myvar = [ [ "list", 2, 3, 4 ], [ 'A', 'B', 'C' ] ]
so if you want to create a nested list in an __init__ function:
class Spam:
def __init__(self):
self.eggbasket = [ [ "list", 2, 3, 4 ], [ 'A', 'B', 'C' ] ]
to assign a nested list to a class attribute. If you are passing in
information
which you wish to assign that way, you would embed it in the given syntax.
For
instance:
class Spam:
def __init__(self, eggs):
self.eggbasket = [ eggs, [ "spam", "spam", "spam" ] ]
my_spam = Spam([ "egg", "egg", "egg"])
which would nest the given list of eggs within the eggbasket member of
my_spam.
You might alternately want to make a copy of the initializer instead of
storing
a reference:
class Spam:
def __init__(self, eggs):
self.eggbasket = [ eggs[:], [ "spam", "spam", "spam" ] ]
[:] (slice of all) is the Pythonic "shallow" list copier.
Of course this is all potentially nonsense as, again, I don't exactly know
what
you are wanting to do.
----- Original Message -----
From: "Bartok" <JollyRoger at hotmail.com>
Subject: Newbie question about nested lists and constructor functions...
> I need some help with nested lists when using class constructors to
> initialize their contents. I found the tutorial to be of not much help in
> this area and have tried everything that I can think of.
>
> I understand the process as I am an experienced C++ programmer but I seem
to
> be having some difficulty using the correct syntax. Can anyone please
help?
More information about the Python-list
mailing list