Identity and equivalence Python is and ==

Not only Python, but many other languages have this concept. Let's take Python as an example.

"Same" and "equivalent"

The word "same" has two meanings. "Same" and "equivalent".

"Mr. A and Mr. B live in the same house."

What do you mean? Most people will think that Mr. A and Mr. B live together. In other words, Mr. A and Mr. B live in the "same" house.

"Mr. A and Mr. B are wearing the same clothes."

What do you mean? I think that few people think that Mr. A and Mr. B are wearing "same" clothes, that is, two people are wearing one piece of clothes. It is natural to think that Mr. A and Mr. B are wearing clothes respectively, and that the clothes that Mr. A is wearing and the clothes that Mr. B is wearing are, for example, clothes of the same manufacturer and the same design. is.

Perhaps the thing itself is different, but in some sense it can be called the same. These relationships are called equivalence or equivalence.

Implementation is required to determine equivalence

By the way, if it is not a simple thing like an integer but a complicated thing like clothes, you have to think about what is considered to be "equivalent". If clothing sizes are included in the criteria, if A and B have different sizes, no matter how similar they are, they will not be considered equivalent. If you don't include clothing size in your criteria, if you're an apparel clerk and a customer tells you to replace it with clothing of the same price, you may bring a different size. Maybe.

Also, if you write it down, in many cases, if it is "same", it will be "equivalent". However, this is not always the case, as it depends on what is considered "equivalent".

Why is it necessary to distinguish between the same and the equivalent?

"Mr. A and Mr. B are in the same car. Mr. A's car crashed into the wall vigorously."

Is Mr. B safe?

If Mr. A and Mr. B were in the same car, Mr. B would not be safe either. Even if Mr. A and Mr. B are in the same car (of the same model), if they are not in the same car, Mr. B has nothing to do with it.

"Variable a and variable b point to the same list. I removed an element from the list of variable a."

Has the element been removed from the list of variables b?

If variable a and variable b are the same, the element has also been removed from the list of b. If the variable a and the variable b are equivalent, but not the same, the list of b is preserved.

In this way, "identical" and "equivalent" are similar and non-conceptual concepts, but in general, the same value is used more often than the same value. The distinction between equivalence and equivalence is often required when the comparison is to a mutable object, such as a list. In a processing system like Python that allocates memory invisible to the programmer, it is rarely necessary to consider whether immutable objects actually point to the same object. As a result, is is rarely used for immutable objects.

What are the operators for checking identity and equivalence in Python?

In Python, the operator that checks for equivalence is is, and the operator that checks for equivalence is ==. Also, the operator that checks for non-equivalence is is not, and the operator for checking for non-equivalence is! =.

The operators ==,! = Can be overloaded by special method names. (That is, you can define how to compare equivalence by creating a method with a special name.) Operators that check for identity cannot be overloaded.

In Python2, there are two special method names that overload == (but since Python 2.1). In Python3, one was abolished and became one type.

The special method names that can be used in both Python 2 (but Python 2.1 or later) and 3 are `__eq__ (self, other)` corresponding to == and `__ne__ (self, other)` corresponding to! =. .. If you're going to make it in the future, don't hesitate to use it if you don't plan to run it on Python 2.1 or earlier.

Here is a code example.

``````class Car:
def __init__(self, maker, model, color, owner):
self.maker = maker
self.model = model
self.color = color
self.owner = owner
def __eq__(self, other):
try:
if (self.maker == other.maker and self.model == other.model and
self.color == other.color):
return True  #Even if the owners are different, they are considered to be the same car
except AttributeError:
pass
return False
def __ne__(self, other):
return not self == other

my_car = Car("Nissan", "GT-R", "Red", "my name")
your_car = Car("Nissan", "GT-R", "Red", "your name")
his_car = Car("Nissan", "Note", "Blue", "his name")

my_garage = [my_car]

print(my_car == your_car) # ==> True
print(my_car == his_car) # ==> False
print(my_car is my_car) # ==> True
print(my_car is my_garage[0]) # ==> True
print(your_car is my_garage[0]) # ==> False
print(your_car == my_garage[0]) # ==> True
``````

Also, the special method `__cmp__ (self, other)` that can be used only in Python2 is an operator that defines six operators <, <=, ==,! =,> =,> At once, and`__cmp__ (self) If, other)`is negative, it means <, if it is 0, it means ==, and if it is positive, it means>. I do not recommend it at all because it can not be used in 3, but it seems that int is implemented in `__cmp__` even in Python 2.7 series, so I will introduce it just in case.

It's a snake leg. With the new method, in order to implement magnitude comparison, you have to define `__ne__`, `__lt__`,` __le__`, `__ge__`,` __gt__` in addition to `__eq__`, but Python 2.7 In subsequent and 3, by using functools.total_ordering, `__eq___` and` __lt__`, `__le__` If you define one of, `__ge__`,` __gt__`, the rest will be done for you.

Other

Is it possible that the Python built-in classes are the same but not the same?

Floating-point nan (not a number) is not equivalent by any comparison. Therefore, it is not the same value when compared with myself.

``````nan = float("nan")
print(nan is nan)  # ==> True
print(nan == nan)  # ==> False
``````

I've heard that you should use is instead of == when comparing to None. why?

If ==, as mentioned above, the user can implement it as he / she likes, so in some cases, exceptions such as TypeError and AttributeError may appear, True may be returned even though it is not None, and processing may be heavy. Hmm. However, if you compare with is, you can definitely compare whether the value is None or not. However, this is because it is [guaranteed by the language specification] that there is only one object with the value of None (http://docs.python.jp/2/reference/datamodel.html#types). You can do it. This usage is a source of trouble when there can be multiple objects with the same value.

Is or ==, which is faster?

Basically, is is faster. However, there are few situations where you can use either one.

Comparing ints with is, they are the same. Does it mean that int comparison can be is?

The same value may or may not be the same. Use == to compare ints unless you want to check for identity for some special purpose.

Same as above.

Is is like JavaScript ===, isn't it?

wrong. Since === in JavaScript is an operator that checks if they are equivalent without type conversion, we are checking if they are equivalent. Python is is checking to be identical. To do something similar in Python, consider, for example, `type (a) is type (b) and a == b`.