Constructor re-initialization issue
Michael Mabin
d3vvnull at gmail.com
Tue Jun 3 19:13:42 EDT 2008
Changing the default for data to None and creating a new dict inside your
function might handle this. But I don't know what it is you want. It never
even occurred to me that this behavior might be desired in the first place.
class Param(object):
def __init__(self,data=None,condition=False):
if data is None:
data = {}
if condition:
data['class'] = 'Advanced'
print data
Param(condition=True)
Param(condition=False)
I always thought you didn't want to have empty sequences as default values.
On Tue, Jun 3, 2008 at 5:11 PM, <pythonreptile at gmail.com> wrote:
> Hello all,
>
> I have come across this issue in Python and I cannot quite understand
> what is going on.
>
> class Param():
> def __init__(self, data={}, condition=False):
> if condition:
> data['class']="Advanced"
> print data
>
> In the previous example, I expect the variable data to be re-
> initialized every time I construct an object type Param. However, when
> I do the following:
>
> Param(condition=True)
> Param(condition=False)
>
> The second call still prints {'class': 'Advanced'}
>
> Shouldn't data be initialized to {} since it is the default in
> __init__? Why would the state of data be preserved between two
> independent instantiations?
>
> Any help would be greatly appreciated.
>
> M.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
| _ | * | _ |
| _ | _ | * |
| * | * | * |
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080603/a54a37dd/attachment-0001.html>
More information about the Python-list
mailing list