0

I am not sure why there is difference when checking or comparing properties of object. Object construtor:

class FooBarObject():
    def __init__(self, val_1, val_2):
        self.val_1 = val_1
        self.val_2 = val_2

Object is created:

obj = FooBarObject(val_1 = "gnd", val_2 = 10). 

I have noticed that I get different results when:

obj.val_1 is "gnd"
obj.val_1 == "gnd"
>>> False
>>> True

What am I doing wrong here?

Tim
  • 41,901
  • 18
  • 127
  • 145
lskrinjar
  • 5,483
  • 7
  • 29
  • 54
  • 3
    `is` tests for *object identity*, `==` tests for *equality*. There is world of different between the tests. If two references are pointing to two different objects, identity testing will fail, but these two objects can still test as *equal*. – Martijn Pieters May 12 '14 at 12:42
  • Not quite sure. If I only check or compare values of attributes I get right result val_1 = "gnd" val_2 = 10 val_1 is "gnd" val_2 == "gnd" >>>True >>>True – lskrinjar May 12 '14 at 12:48
  • The interpreter can *reuse* existing string objects as an optimisation, but you shouldn't *rely* on the behaviour. – Martijn Pieters May 12 '14 at 12:50
  • @MartijnPieters my answer is refering to your first post. The two references point to one object and one object's property. Only two different functions are used to compare values. – lskrinjar May 12 '14 at 12:52

2 Answers2

3
obh.val_1 is "gnd"

compares the two objects in memory if they are the same object. Python sometimes interns strings in order to reuse them if they are identical. Using "is" to compare strings will not always have predictable results. In another sense, you sort of called

id(obh.val_1) == id("gnd") #id demonstrates uniqueness

Use "==" for string equality to achieve your intention.

Roy Iacob
  • 412
  • 3
  • 13
2

When you use the "==" you are comparing the content of the variables in the memory , so any match will result "True" , but when using "is" ,the address in the RAM needs to be the same and so this will result a false since they're stored iin diffrent places in the memory