473,467 Members | 2,005 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

instance variable weirdness

Hello,

I have written the following script to illustrate a problem in my code:

class BaseClass(object):
def __init__(self):
self.collection = []

class MyClass(BaseClass):
def __init__(self, name, collection=[]):
BaseClass.__init__(self)
self.name = name
self.collection = collection

if __name__ == '__main__':
seq = []
inst = None
for i in xrange(5):
inst = MyClass(str(i))
inst.collection.append(i)
seq.append(inst)
inst = None
for i in xrange(5):
inst = MyClass(str(i)+'~', [])
inst.collection.append(i)
seq.append(inst)
inst = None
for i in seq:
print "Instance '%s'; collection = %s" % (i.name,
str(i.collection))

The output I get is:
Instance '0'; collection = [0, 1, 2, 3, 4]
Instance '1'; collection = [0, 1, 2, 3, 4]
Instance '2'; collection = [0, 1, 2, 3, 4]
Instance '3'; collection = [0, 1, 2, 3, 4]
Instance '4'; collection = [0, 1, 2, 3, 4]
Instance '0~'; collection = [0]
Instance '1~'; collection = [1]
Instance '2~'; collection = [2]
Instance '3~'; collection = [3]
Instance '4~'; collection = [4]


I don't understand why the first loop doesn't give the same result as
the second loop. Can somebody enlighten me?

Wietse

Apr 14 '06 #1
4 996
Em Sex, 2006-04-14 Ã*s 09:18 -0700, wietse escreveu:
def __init__(self, name, collection=[]):
Never, ever, use the default as a list.
self.collection = collection
This will just make a reference of self.collection to the collection
argument.
inst.collection.append(i)


As list operations are done in place, you don't override the
self.collection variable, and all instances end up by having the same
list object.

To solve your problem, change
def __init__(self, name, collection=[]):
BaseClass.__init__(self)
self.name = name
self.collection = collection # Will reuse the list
to
def __init__(self, name, collection=None):
BaseClass.__init__(self)
self.name = name
if collection is None:
collection = [] # Will create a new list on every instance
self.collection = collection
--
Felipe.

Apr 14 '06 #2
Em Sex, 2006-04-14 Ã*s 13:30 -0300, Felipe Almeida Lessa escreveu:
To solve your problem, change
def __init__(self, name, collection=[]):
BaseClass.__init__(self)
self.name = name
self.collection = collection # Will reuse the list
to
def __init__(self, name, collection=None):
BaseClass.__init__(self)
self.name = name
if collection is None:
collection = [] # Will create a new list on every instance
self.collection = collection


Or if None is valid in your context, do:

__marker = object()
def __init__(self, name, collection=__marker):
BaseClass.__init__(self)
self.name = name
if collection is __marker:
collection = [] # Will create a new list on every instance
self.collection = collection

--
Felipe.

Apr 14 '06 #3
On Fri, 14 Apr 2006 13:30:49 -0300, Felipe Almeida Lessa wrote:
Em Sex, 2006-04-14 Ã*s 09:18 -0700, wietse escreveu:
def __init__(self, name, collection=[]):


Never, ever, use the default as a list.


Unless you want to use the default as a list.

Sometimes you want the default to mutate each time it is used, for example
that is a good technique for caching a result:

def fact(n, _cache=[1, 1, 2]):
"Iterative factorial with a cache."
try:
return _cache[n]
except IndexError:
start = len(_cache)
product = _cache[-1]
for i in range(start, n+1):
product *= i
_cache.append(product)
return product
--
Steven.

Apr 14 '06 #4
Em Sáb, 2006-04-15 Ã*s 04:03 +1000, Steven D'Aprano escreveu:
Sometimes you want the default to mutate each time it is used, for example
that is a good technique for caching a result:

def fact(n, _cache=[1, 1, 2]):
"Iterative factorial with a cache."
try:
return _cache[n]
except IndexError:
start = len(_cache)
product = _cache[-1]
for i in range(start, n+1):
product *= i
_cache.append(product)
return product


I prefer using something like this for the general case:

def cached(function):
"""Decorator that caches the function result.

There's only one caveat: it doesn't work for keyword arguments.
"""
cache = {}
def cached_function(*args):
"""This is going to be replaced below."""
try:
return cache[args]
except KeyError:
cache[args] = function(*args)
return cache[args]
cached_function.__doc__ = function.__doc__
cached_function.__name__ = function.__name__
return cached_function

And for this special case, something like:

def fact(n):
"Iterative factorial with a cache."
cache = fact.cache
try:
return cache[n]
except IndexError:
start = len(cache)
product = cache[-1]
for i in range(start, n+1):
product *= i
cache.append(product)
return product
fact.cache = [1, 1, 2]

This may be ugly, but it's less error prone. Also, we don't expose the
cache in the function's argument list.

--
Felipe.

Apr 14 '06 #5

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

Similar topics

34
by: SeeBelow | last post by:
I see the value of a class when two or more instances will be created, but Python programmers regularly use a class when there will only be one instance. What is the benefit of this? It has a...
7
by: Yngve | last post by:
Hi! I am trying to make two pointers at instances of the same class wich is beeing defined. But i get the following error from the compiler (MVC7): -------------------- ...
166
by: Graham | last post by:
This has to do with class variables and instances variables. Given the following: <code> class _class: var = 0 #rest of the class
7
by: ben | last post by:
hello, an algorithm book i'm reading talks about the connectivity problem/algorithm. it gives a number of examples where the connectivity problem applies to real life situations (like, the...
5
by: Brett | last post by:
In a class, I have several Private subs. I declare an instance of the class such as: Dim MySelf as new Class1 within a private sub. The motive is to provide access to other subs within the...
5
by: David Thielen | last post by:
Hi; I am creating png files in my ASP .NET app. When I am running under Windows 2003/IIS 6, the file is not given the security permissions it should have. It does not have any permission for...
6
by: thomson | last post by:
Hi All, In a Singleton pattern , if we create an instance variable, and return it, whether this one also be a static variable , Can anyone give me insights on the Memory allocation Thanks in...
12
by: titan nyquist | last post by:
I have a class with data and methods that use it. Everything is contained perfectly THE PROBLEM: A separate thread has to call a method in the current instantiation of this class. There is...
2
by: JYA | last post by:
Hi. I was writing an xmltv parser using python when I faced some weirdness that I couldn't explain. What I'm doing, is read an xml file, create another dom object and copy the element from...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.