473,394 Members | 1,640 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,394 software developers and data experts.

Class instance problem?

Hi,

I'm new to python and I've come across a problem with my objects
corrupting each other.

class aclass:
num = 0
l = [[],[]]

a = aclass()
b = aclass()
a.l.append(1)
print "a.l",a.l
print "b.l",b.l

My expectation is that a,b are separate objects, but appending to
a's l also appends to b's l. Why does this occur? On the other hand,
the command

a.num = 1

doesn't change b.num's. This is inconsistency is driving me crazy.
What am I doing wrong?

Thanks for any help
Jul 18 '05 #1
5 1338
In article <c0**************************@posting.google.com >,
zh****@princeton.edu (Zhao Huang) wrote:
I'm new to python and I've come across a problem with my objects
corrupting each other.

class aclass:
num = 0
l = [[],[]]

a = aclass()
b = aclass()
a.l.append(1)
print "a.l",a.l
print "b.l",b.l

My expectation is that a,b are separate objects, but appending to
a's l also appends to b's l. Why does this occur? On the other hand,
the command

a.num = 1

doesn't change b.num's. This is inconsistency is driving me crazy.
What am I doing wrong?


When you set num and l in the class body, you're making them class-wide
variables (like static in Java). If you want a different one per
object, you need to set them in the __init__ method.

--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
Jul 18 '05 #2
On 12 May 2004 21:43:25 -0700, zh****@princeton.edu (Zhao Huang)
declaimed the following in comp.lang.python:
Hi,

I'm new to python and I've come across a problem with my objects
corrupting each other.

class aclass:
num = 0
l = [[],[]]

My expectation is that a,b are separate objects, but appending to
a's l also appends to b's l. Why does this occur? On the other hand,
the command
ONE: read the documentation about mutable and immutable objects.
TWO: num and l are not INSTANCE variables, they are class-wide
definitions. Therefore, ALL instances (objects) created from the class
are using the SAME num and l
a.num = 1

doesn't change b.num's. This is inconsistency is driving me crazy.
Refer back to point "ONE".

Now, to cut to the chase, what you WANT is

class aclass:
def __init__(self):
self.num = 0
self.l = [ [], [] ]

This results in INSTANCE specific variables being created when
the object itself is created:
a = aclass()
b = aclass()
a.l.append([1, 2, 3])
a.num = 4
print a.num 4 print a.l [[], [], [1, 2, 3]] print b.num 0 print b.l [[], []]


-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #3
Hello Zhao,
class aclass:
num = 0
l = [[],[]]

a = aclass()
b = aclass()
a.l.append(1)
print "a.l",a.l
print "b.l",b.l

My expectation is that a,b are separate objects, but appending to
a's l also appends to b's l. Why does this occur? On the other hand,
the command

a.num = 1

doesn't change b.num's. This is inconsistency is driving me crazy.
What am I doing wrong?

Several things :-)
First, "num" and "l" are both *class* properties and not object
properties. The right way to do this is:
class aclass:
def __init__(self):
num = 0
l = [[], []]

Each class method has a `self' parameter which is the object that is
currently called. See the tutorial for more explanation on the subject.

Second "num" and "l" are named bounded to the same objects objects both
in a and b. When you do `a.num =1' you change the binding of a.num to 1.
When you do a.l.append you append to the same objects as in b.l.

HTH.
Miki
Jul 18 '05 #4
Zhao Huang wrote:
Hi,

I'm new to python and I've come across a problem with my objects
corrupting each other.

class aclass:
num = 0
l = [[],[]]
These create class attributes, not instance attributes. For example,
after this you can try:

print aclass.num
print aclass.l

a = aclass()
b = aclass()
a.l.append(1)
Since the instance a does not have an 'l' attribute, a.l refers to the
class attribute aclass.l. You can verify this at this point by:

print a.l is aclass.l # 'is' checks identity of objects

Also you do a.l.append(1). The .append() (note the '.') tells python to
append to the referred object. You are calling a method on the list
object and you end up appending to aclass.l.
print "a.l",a.l
print "b.l",b.l
Also try, print a.l is b.l. There is only one list object, it is on the
class aclass but can be referenced through a.l and b.l.
My expectation is that a,b are separate objects, but appending to
a's l also appends to b's l. Why does this occur? On the other hand,
the command

a.num = 1
Aha, here you use the '=' operator. Compare with operation on the list l
earlier, where you used the '.' operator and a method name 'append'. The
'=' creates an instance attribute 'num' on a.
doesn't change b.num's.
Nope, there is no instance attribute 'num' on b as of now. print b.num
merely prints aclass.num.

Now that you know about '=', you can try

a.L = []
b.L = []
a.L.append(1)
print a.L, b.L

And you'll see that you have two distinct lists. Actually three distinct
ones if you count aclass.l. If you only need instance attributes, don't
put them on the class. Use the following:

class aclass:
def __init__(self):
self.L = []
self.num = 0

a = aclass()
b = aclass()
# play with a.L, b.L, a.num, b.num
This is inconsistency is driving me crazy. What am I doing wrong?

Hope the above helped.

Thanks for any help


--
Shalabh
Jul 18 '05 #5
On Thu, 13 May 2004 08:04:29 +0200, Miki Tebeka wrote:
Hello Zhao,
class aclass:
num = 0
l = [[],[]]

a = aclass()
b = aclass()
a.l.append(1)
print "a.l",a.l
print "b.l",b.l

My expectation is that a,b are separate objects, but appending to
a's l also appends to b's l. Why does this occur? On the other hand,
the command

a.num = 1

doesn't change b.num's. This is inconsistency is driving me crazy.
What am I doing wrong?

Several things :-)
First, "num" and "l" are both *class* properties and not object
properties. The right way to do this is:
class aclass:
def __init__(self):
num = 0
l = [[], []]


You surely intended:

class aclass:
def __init__(self):
self.num = 0
self.l = [[], []]

(for Zhao's mental sanity)

Riccardo

--
-=Riccardo Galli=-

_,e.
s~ ``
~@. ideralis Programs
.. ol
`**~ http://www.sideralis.net
Jul 18 '05 #6

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

Similar topics

1
by: Murat Tasan | last post by:
hi, i am having a small problem with constructing an inner class. i am using an inner class (and not a static nested class) because the methods of the inner class need access to the enclosing...
7
by: Rim | last post by:
Hi, It appears to me the simplest way to add a function to a class outside of the class declaration is as follows: >>> class a(object): .... pass .... >>> def f(self): .... print 'hi'
8
by: Mark English | last post by:
I'd like to write a Tkinter app which, given a class, pops up a window(s) with fields for each "attribute" of that class. The user could enter values for the attributes and on closing the window...
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
10
by: Opa | last post by:
I have tried for two days to solve this problem with no luck. I have a singleton class which has some events declared. When I inherit from this class the events don't seem to come along with it....
21
by: Mark Broadbent | last post by:
Consider the following statements //------- Item i = Basket.Items; //indexer is used to return instance of class Item Basket.Items.Remove(); //method on class item is fired item i = new...
7
by: jsale | last post by:
I have made an ASP.NET web application that connects to SQL Server, reading and writing data using classes. I was recommended to use session objects to store the data per user, because each user...
29
by: Michael D. Ober | last post by:
Is there any way to create a constant in a class that can be used both with an instantiated object and without. For example: dim ClassConst as string = myClass.ConstantString dim myObj = new...
26
by: nyathancha | last post by:
Hi, How Do I create an instance of a derived class from an instance of a base class, essentially wrapping up an existing base class with some additional functionality. The reason I need this is...
20
by: tshad | last post by:
Using VS 2003, I am trying to take a class that I created to create new variable types to handle nulls and track changes to standard variable types. This is for use with database variables. This...
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: 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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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...
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...

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.