Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top