How do I pass a list to a __init__ value/definition?
Bruno Desthuilliers
onurb at xiludom.gro
Tue Jul 25 09:11:31 EDT 2006
ryanshewcraft at gmail.com wrote:
> Let me start with my disclaimer by saying I'm new to computer
> programming and have doing it for the past three weeks. I may not be
> completely correct with all the jargon, so please bear with me.
>
> Anyways, I'm writing a function which has a class
<ot>
While legal (in Python) and sometimes handy, it's somewhat uncommon to
define classes in functions. Perhaps a problem with jargon ?-)
</ot>
> called
> "MultipleRegression." I want one of the variables under the __init__
> method to be a list.
Then pass in a list.
> I've got:
>
> class MultipleRegression:
> def __init__(self, dbh, regressors, fund):
> self.dbh = dbh
> self.regressors = regressors
>
> and I want to be able to enter regressors as a list like
> MultipleRegression(dbh, [1,2,3,4], 5). But when I do this only the 1
> gets passed to regressors and thus to self.regressors.
Using your code (copy-pasted for the class definition), I get this result:
>>> m = MultipleRegression('dbh', [1,2,3,4], 5)
>>> m.regressors
[1, 2, 3, 4]
>>>
Looks like you didn't send the real minimal code sample exposing the
problem.
FWIW, one possible cause would be misunderstanding of the concept of
'reference', ie :
>>> regressors = [1, 2, 3, 4]
>>> m1 = MultipleRegression('dbh', regressors, 5)
>>> m1.regressors
[1, 2, 3, 4]
>>> regressors.append(42)
>>> m1.regressors
[1, 2, 3, 4, 42]
>>>
If this happens to be your real problem, you can solve it by storing a
*copy* of the regressors list. Depending on what you really store in
'regressors', you'll need a simple copy or a deep copy:
1/ simple copy, suitable if regressors list items are immutable
(numerics, strings, tuples, ...) or if it's ok to have references to
(not copies of) these items:
class MultipleRegression:
def __init__(self, dbh, regressors, fund):
self.dbh = dbh
self.regressors = regressors[:] # makes a copy of the list
2/ deep copy, in case you need it (but read the Fine Manual before...):
import copy
class MultipleRegression:
def __init__(self, dbh, regressors, fund):
self.dbh = dbh
self.regressors = copy.deepcopy(regressors)
> I really am getting into this whole programming thing.
> Its real challenging and very useful for my work.
Welcome onboard !-)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list