Class instance problem?
Shalabh Chaturvedi
shalabh at cafepy.com
Thu May 13 01:15:04 EDT 2004
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
More information about the Python-list
mailing list