473,606 Members | 2,101 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

always the same object (2)

Hi,

sorry for the lack of source code.
Here again:

I use struct.unpack() to unpack data from a binary file and pass the
returned tuple as parameter to __init__ of a class that's supposed to
handle the data:

class DataWrapper():
data = { }
def __init__(self, arg): #arg will contain a tuple
data['var1'], data['var2'] = arg
result = [ ]
while not <end-of-file f>:
data = struc.unpack("4 s4s", f.read(8))
record = DataWrapper( data ) # pass tuple from unpack
result.append( record )

Then "result" contains a list with different objects, but the strings
in data['var1'] and data['var2'] are all the same.

Any ideas how to avoid this?

Thanks again
Ciao
Uwe
Jul 18 '05 #1
2 1601
Uwe Mayer wrote:

Thanks for all the responses. As John Roth <ne********@jhr othjr.com> wrote
in <10************ *@news.supernew s.com>:
class DataWrapper():
data = { }
def __init__(self, arg): #arg will contain a tuple
data['var1'], data['var2'] = arg
the "data" variable is a class variable and shared by all DataWrapper,
therfore:
result = [ ]
while not <end-of-file f>:
data = struc.unpack("4 s4s", f.read(8))
record = DataWrapper( data ) # pass tuple from unpack
result.append( record )


all "record"s in "result" share the same instance and thus all the data gets
overwritten. :)

Moving "data" into __init__() in DataWrapper does the trick.

Thanks again
Ciao
Uwe
Jul 18 '05 #2
Uwe Mayer <me*****@hadiko .de> writes:

(...)
I use struct.unpack() to unpack data from a binary file and pass the
returned tuple as parameter to __init__ of a class that's supposed to
handle the data:

class DataWrapper():
data = { }
def __init__(self, arg): #arg will contain a tuple
data['var1'], data['var2'] = arg
Is this actual code? You should get a SyntaxError on your use of ()
in the class line, and a NameError on your use of data[] since there
is no local data name within the __init__ function. I'm assuming your
real code actually does self.data, and skips the () on the class
statement, but in the future, it's really best if you can post actual
operating code when discussing a problem.
result = [ ]
while not <end-of-file f>:
data = struc.unpack("4 s4s", f.read(8))
record = DataWrapper( data ) # pass tuple from unpack
result.append( record )

Then "result" contains a list with different objects, but the strings
in data['var1'] and data['var2'] are all the same.

Any ideas how to avoid this?


Yes, don't make data a class-level object. By doing this you have a
single instance of the dictionary that data is pointing to, which is
shared among all of your DataWrapper instances. Since that class
object is mutable, all of your changes in each instances __init__
affect that single object. Instead, move the creation of the instance
name (and object) to the __init__ in your instance.

This can be a subtle point sometimes, because you won't run into this
problem with class level immutable objects (such as ints), because any
assignment to the same name in an instance becomes a rebinding
operation, thus making the name an instance variable at that point in
time. This can be very convenient for implementing class level
defaults that take up no space in each instance, but doesn't work the
same as mutable types.

Note that if you really mean to do it, using a mutable type at class
level can be a very useful construct, since it permits sharing of
information among all instances of a class. But you have to be
expecting it :-)

For example, the immutable case:
class Foo: ... var = 10
... def set_var(self, value):
... print 'Var ID:', id(self.var)
... self.var = value
... print 'Var ID:', id(self.var)
... x = Foo()
print id(Foo.var), id(x.var) 7649236 7649236 x.set_var(5) Var ID: 7649236
Var ID: 7649224 print id(Foo.var), id(x.var) 7649236 7649224 print Foo.var, x.var 10 5

Foo.var always references the same object, but once an assignment has
been made within the instance, it no longer points to the same object
as initialized at class level. Thus, each instance references
independent objects with their own values.

Contrast this with the mutable case:
class Foo: ... var = []
... def set_var(self, value):
... print 'Var ID:', id(self.var)
... self.var.append (value)
... print 'Var ID:', id(self.var)
... x = Foo()
y = Foo()
print id(Foo.var), id(x.var), id(y.var) 8042256 8042256 8042256 print Foo.var, x.var, y.var [] [] [] x.set_var(10) Var ID: 8042256
Var ID: 8042256 y.set_var(5) Var ID: 8042256
Var ID: 8042256 print id(Foo.var), id(x.var), id(y.var) 8042256 8042256 8042256 print Foo.var, x.var, y.var [10, 5] [10, 5] [10, 5]

I made the class object a list and appended values to it just to
highlight how calls to multiple instances were affecting the same
object, but the principle is the same with a dictionary or any other
mutable object. Since the changes in set_var are made by mutating the
existing object (versus rebinding the same name to a new object), all
the instances share the single Foo.var list.

So you could use this construct if you really wanted an object that
was seen by all instances and updated by any instance. But if you
just wanted an empty list (or dictionary) independently in each
instance, you'd want to do something like:
class Foo: ... def __init__(self):
... self.var = []
... def set_var(self, value):
... print 'Var ID:', id(self.var)
... self.var.append (value)
... print 'Var ID:', id(self.var)
... x = Foo()
y = Foo()
print id(Foo.var) Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: class Foo has no attribute 'var' print id(x.var), id(y.var) 7756800 8053200 x.set_var(10) Var ID: 7756800
Var ID: 7756800 y.set_var(5) Var ID: 8053200
Var ID: 8053200 print id(x.var), id(y.var) 7756800 8053200 print x.var, y.var

[10] [5]

-- David
Jul 18 '05 #3

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

Similar topics

3
1631
by: Uwe Mayer | last post by:
Hi, I am using struct.unpack() quite often. unpack() returns a tuple, however a tuple with always the same id(), which is AFAIK the memory location of the structure. I found myself working with above tuple, initialising other data structures, etc... and when I tried to change one list element, suddenly all list elements change => so they all contain the identical object
2
6478
by: Claire Reed | last post by:
Dear All, I am repeatedly encountering a problem whilst looping through XML Nodes and I am unsure as to what is going on and how I can get around it. I load the following XML document into an XmlDocument object using LoadXml: <?xml version="1.0" encoding="UTF-8"?>
3
1964
by: Adam | last post by:
Hi all, I have an arraylist filled with 4 objects and defined as shown below. ArrayList items = new ArrayList(); public Item GetItemAt(int index) { return (Item)items; }
5
2185
by: Haydnw | last post by:
Hi, I have the code below as code-behind for a page which displays two images. My problem is with the second bit of code, commented as " 'Portfolio image section". Basically, the SQL query gets details of a random image from an access database. I know this works because when I run the query in access, it picks a different image each time (or close enough). However, when I view the .aspx page that this code-behind is for, it always picks...
12
2123
by: tobias.sturn | last post by:
Hi! My prof told me always to make my members private or protected cause its standard to write setter and getter methodes.. Is that in your opinion correct? Cause I dont see any adventages to write a member of a class private if there are no side effects in changing the variable. I think you only have to write more (the getter and setters) the code gets bigger... Thanks very much!
0
1349
by: vincenzoelettronico | last post by:
I am making the pages asp of one library on-linens with visual study 2003. I have created the datagrid, the subroutine UpdateCommand. .now I want to avoid to always insert the same element. .someone says me like making? I would have to make a IF. .but like? In order to help to understand you, I put you the code vb and that asp of mine web form! Imports System.Data.SqlClient
2
1592
by: mikeficklonni | last post by:
Hello, I am very new to C# and .Net. I may be overlooking something very simple here, however, even after reading several forums I'm still stumped. I can't get the HasChanges method to work. It always returns false. I have a dataset on the form (DSCustRow), which is loaded by a different class. My binding seems to work as the data appears on the form. When I press the save button, I check for changes on the dataset. The result is...
8
1584
by: raylopez99 | last post by:
Hi, Best practices question. When receiving an object passed from another method, is it a good idea to use a shallow copy with a temporary object received on the RHS (right hand side of =), or to use a instantiated object to receive the object on the RHS? Since I may be using the wrong lingo, to put it more concretely.
16
1827
by: Jonathan Wood | last post by:
Greetings, I was wondering if anyone here has a good understaning of the Session object. I know there are options like the Session.Abandon method and the regenerateExpiredSessionId setting, although I do not understand what they do. Can anyone tell me if it's possible for a recycled session to still contain the old data? I had a couple of reports that where users said they logged on and saw another user's data. On this site, there...
0
8009
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7939
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8432
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8428
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8078
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
5962
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3964
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2442
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 we have to send another system
1
1548
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.