Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple instances of a class being overwritten at the same time? (Python)

Here's a very simple code I made to demonstrate the problem I'm encountering. What's happening here is that I'm creating two different instances of the same class but changing an attribute of one will change the corresponding attribute of the other instance. I'm not sure why this is. Is this normal in Python or am I encountering something being totally messed up?

class exampleClass(object):

    attribute1=0
    attribute2="string"

x=exampleClass
x.attribute1=20
x.attribute2="Foo"

y=exampleClass
y.attribute1=60
y.attribute2="Bar"

print("X attributes: \n")
print(x.attribute1)
print(x.attribute2)

print("Y attributes: \n")
print(y.attribute1)
print(y.attribute2)

Here is what the program looks like coming out of my console:

>>> 
X attributes: 

60
Bar
Y attributes: 

60
Bar
>>> 

I think it should be saying:

X attributes:

20
Foo
Y attributes:

60
Bar

What am I doing wrong?

like image 545
jecaklafa Avatar asked Jun 26 '12 23:06

jecaklafa


1 Answers

You're creating class attributes, when you want instance attributes. Use this:

class exampleClass(object):
    def __init__(self):
        self.attribute1 = 0
        self.attribute2 = "string"

Also, you aren't creating any instances of exampleClass, you need this:

x = exampleClass()
y = exampleClass()

Your code is simply using new names for the class, and changing its attributes.

like image 118
Ned Batchelder Avatar answered Nov 15 '22 22:11

Ned Batchelder