Why is 'is' returning true for a different instance in Python [duplicate]
Why is 'is' returning true for a different instance in Python [duplicate]
This question already has an answer here:
This is a python beginner question:
class MyClass:
variable = "test"
def function(self):
print("test")
X = MyClass()
Y = MyClass()
print (X.variable == Y.variable) // expected true, works
print (X.variable is Y.variable) // expected false, but return true; why?
Since there are two instances of the class, why is the second test with 'is' returning true since the variables should be difference instances?
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
2 Answers
2
In the example you've provided, variable is a class attribute on MyClass. All instances of MyClass will share the same variable instance. If you want to provide an instance variable to an instance of the class, you would do so in the __init__ method like so:
variable
MyClass
MyClass
variable
__init__
class MyClass:
shared_var = "I'm a property on the class"
def __init__(self):
self.my_var = "I'm a property on an instance"
Note, however, that even if you were to do the following:
x = MyClass()
y = MyClass()
x.my_var is y.my_var # This will still be True!
This is because the two strings actually reference the same object in Python. You can see this by typing the following in a Python interpretor:
id('test')
id('test') # This will be the same as the one above!
I'm learning the syntax of python; so variables declared just below the class name are considered static? how do you set the variable as part of the instance of the class?
– Thomas
Sep 9 '18 at 18:37
It is not a static method, but a "class attribute".
– wim
Sep 9 '18 at 18:38
Whoops, good call @wim
– Kirollos Morkos
Sep 9 '18 at 18:40
@Thomas you would want to declare instance variables in the
__init__ method. I'll update my answer to provide an example.– Kirollos Morkos
Sep 9 '18 at 18:41
__init__
@Thomas probably important to note, but Python doesn't have variable declarations
– juanpa.arrivillaga
Sep 9 '18 at 18:50
Because "variable" is class or static variable. If you define it inside method, you will be correct. Please look here: Are static class variables possible?
"Static variable" is barely a good name in C; it has no meaning whatsoever in Python. It's a class attribute.
– chepner
Sep 9 '18 at 18:51
Related: How to avoid having class data shared among instances?
– Aran-Fey
Sep 9 '18 at 18:33