0

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?

Thomas
  • 10,933
  • 14
  • 65
  • 136

2 Answers2

1

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:

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!
Kirollos Morkos
  • 2,503
  • 16
  • 22
0

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?

kur ag
  • 591
  • 8
  • 19
  • 1
    "Static variable" is barely a good name in C; it has no meaning whatsoever in Python. It's a class attribute. – chepner Sep 09 '18 at 18:51