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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With