473,382 Members | 1,392 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 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 1653
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
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.