472,988 Members | 3,087 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,988 software developers and data experts.

strange behaviour with keyword arguments and inheritance

Check out this toy example that demonstrates some "strange" behaviour
with keyword arguments and inheritance.

=================================

class Parent:
def __init__(self, ary = []):
self.ary = ary

def append(self):
self.ary.append(1)

class Child(Parent):
def __init__(self):
Parent.__init__(self)
self.append()

def main():
a = Child()
print a.ary
b = Child()
print b.ary

main()

=====================================

You would think the output of this program would be [1], [1]. But
strangely enough the output is [1,], [1,1]. I suppose that the
Parent.__class__ object is only created once and thus the keyword
argument always refers to the same thing, but I don't know. I have a
very rudimentary understading of python's guts, but I would still call
the behaviour unexpected. Or perhaps I should rtfm?

Any thoughts would be much appreciated. Thanks.

Apr 17 '07 #1
8 1623
On Apr 17, 8:56 am, "matthewperpick" <matthewperp...@gmail.comwrote:
Check out this toy example that demonstrates some "strange" behaviour
with keyword arguments and inheritance.

=================================

class Parent:
def __init__(self, ary = []):
self.ary = ary

def append(self):
self.ary.append(1)

class Child(Parent):
def __init__(self):
Parent.__init__(self)
self.append()

def main():
a = Child()
print a.ary
b = Child()
print b.ary

main()

=====================================

You would think the output of this program would be [1], [1]. But
strangely enough the output is [1,], [1,1]. I suppose that the
Parent.__class__ object is only created once and thus the keyword
argument always refers to the same thing, but I don't know. I have a
very rudimentary understading of python's guts, but I would still call
the behaviour unexpected. Or perhaps I should rtfm?

Any thoughts would be much appreciated. Thanks.
A slight modification of init-ing the parent can give you the expected
output.

class Child(Parent):
def __init__(self):
Parent.__init__(self, [])
self.append()
Apr 17 '07 #2
On Apr 17, 8:56 am, "matthewperpick" <matthewperp...@gmail.comwrote:
Check out this toy example that demonstrates some "strange" behaviour
with keyword arguments and inheritance.

=================================

class Parent:
def __init__(self, ary = []):
self.ary = ary
This should work:

class Parent:
def __init__(self, ary = []):
self.ary = list(ary)

And FYI
http://groups.google.com/group/comp....89b250ceca1458

Apr 17 '07 #3
On Apr 17, 9:36 am, livibetter <livibet...@gmail.comwrote:
On Apr 17, 8:56 am, "matthewperpick" <matthewperp...@gmail.comwrote:
Check out this toy example that demonstrates some "strange" behaviour
with keyword arguments and inheritance.
=================================
class Parent:
def __init__(self, ary = []):
self.ary = ary

This should work:

class Parent:
def __init__(self, ary = []):
self.ary = list(ary)

And FYIhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...
livibetter has a better solution. the reason is that you need to
create a new list object everytime, am I right?

Apr 17 '07 #4
Ju**********************@gmail.com wrote:
On Apr 17, 9:36 am, livibetter <livibet...@gmail.comwrote:
>On Apr 17, 8:56 am, "matthewperpick" <matthewperp...@gmail.comwrote:
>>Check out this toy example that demonstrates some "strange" behaviour
with keyword arguments and inheritance.
=================================
class Parent:
def __init__(self, ary = []):
self.ary = ary
This should work:

class Parent:
def __init__(self, ary = []):
self.ary = list(ary)

And FYIhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...

livibetter has a better solution. the reason is that you need to
create a new list object everytime, am I right?
Yes, specifically on every *call*.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings http://holdenweb.blogspot.com

Apr 17 '07 #5
Steve Holden <st***@holdenweb.comwrote:
...
livibetter has a better solution. the reason is that you need to
create a new list object everytime, am I right?
Yes, specifically on every *call*.
....and livibetter's solution also creates a new list on every call to
Child (that [] passed on to Parent.__init__ does exactly that).
Alex
Apr 17 '07 #6
matthewperpick a écrit :
Check out this toy example that demonstrates some "strange" behaviour
with keyword arguments and inheritance.
Nope. It demonstrates that default arguments are eval'd only once (when
the def statement is eval'd), which is documented and a FAQ.
I have a
very rudimentary understading of python's guts, but I would still call
the behaviour unexpected. Or perhaps I should rtfm?
Well, since you mention it... !-)

Apr 17 '07 #7

matthewperpick wrote:
Check out this toy example that demonstrates some "strange" behaviour
with keyword arguments and inheritance.

=================================

class Parent:
def __init__(self, ary = []):
self.ary = ary
[snip]

As pointed out earlier, default values for arguments are evaluated
when the function is defined, not when it is called. This creates
confusion if this value is mutable and later mutated; I got confused
by it when I started python. So it is often not a good idea to use
mutable objects as default arguments.

A simple fix:

def __init__(self, ary=None):
if ary is None: ary = []
self.ary = ary

--
Arnaud

Apr 17 '07 #8
cool .. thanks everyone. here is the aforementioned faq.

http://www.python.org/doc/faq/genera...etween-objects

On Apr 17, 5:16 am, Arnaud Delobelle <arno...@googlemail.comwrote:
matthewperpick wrote:
Check out this toy example that demonstrates some "strange" behaviour
with keyword arguments and inheritance.
=================================
class Parent:
def __init__(self, ary = []):
self.ary = ary

[snip]

As pointed out earlier, default values for arguments are evaluated
when the function is defined, not when it is called. This creates
confusion if this value is mutable and later mutated; I got confused
by it when I started python. So it is often not a good idea to use
mutable objects as default arguments.

A simple fix:

def __init__(self, ary=None):
if ary is None: ary = []
self.ary = ary

--
Arnaud

Apr 17 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

24
by: brian.bird | last post by:
Can anyone explain the behaviour of python when running this script? >>> def method(n, bits=): .... bits.append(n) .... print bits .... >>> method(1) >>> method(2)
20
by: talin at acm dot org | last post by:
Although I realize the perils of even suggesting polluting the Python namespace with a new keyword, I often think that it would be useful to consider defining an operator for testing whether or not...
6
by: Edd Dawson | last post by:
Hi. I have a strange problem involving the passing of command line arguments to a C program I'm writing. I tried posting this in comp.programming yesterday but someone kindly suggested that I'd...
31
by: DeltaOne | last post by:
#include<stdio.h> typedef struct test{ int i; int j; }test; main(){ test var; var.i=10; var.j=20;
9
by: Karahan Celikel | last post by:
Here are three simple classes: class A { public void DoIt(B b) { DoSomething(b); } public void DoSomething(B b) {
14
by: Zeng | last post by:
Would somebody know when we should seal a class? Shouldn't all classes be open up for inheritance? Thanks!
3
by: flat_ross | last post by:
For anyone who is just getting into VB.NET and/or is starting to work with inheritance I would like to point out a potential pitfall. We found this confusion recently when code-reviewing an...
6
by: Peter Oliphant | last post by:
I just discovered that the ImageList class can't be inherited. Why? What could go wrong? I can invision a case where someone would like to add, say, an ID field to an ImageList, possible so that...
20
by: Pilcrow | last post by:
This behavior seems very strange to me, but I imagine that someone will be able to 'explain' it in terms of the famous C standard. -------------------- code -----------------------------------...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
3
SueHopson
by: SueHopson | last post by:
Hi All, I'm trying to create a single code (run off a button that calls the Private Sub) for our parts list report that will allow the user to filter by either/both PartVendor and PartType. On...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.