Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: class override "is" behavior

Tags:

I'm writing a class which encapsulates any arbitrary object, including simple types. I want the "is" keyword to operate on the encapsulated value, such as this behavior:

Wrapper(True) is True -> True Wrapper(False) is True -> False Wrapper(None) is None -> True Wrapper(1) is 1 -> True 

Is there any object method I can override to get this behavior?

like image 512
Heinrich Schmetterling Avatar asked Oct 22 '10 01:10

Heinrich Schmetterling


People also ask

Is operator overriding possible in Python?

The operator overloading in Python means provide extended meaning beyond their predefined operational meaning. Such as, we use the "+" operator for adding two integers as well as joining two strings or merging two lists. We can achieve this as the "+" operator is overloaded by the "int" class and "str" class.

How do you override Python?

In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.

What is __ IADD __ in Python?

iadd() :- This function is used to assign and add the current value. This operation does “a+=b” operation.


2 Answers

No. is, and, and or cannot be overloaded.

like image 102
Ignacio Vazquez-Abrams Avatar answered Oct 22 '22 05:10

Ignacio Vazquez-Abrams


Generally, if you want to test equality in terms of value (if x is 1, or True, or None), you'd use the == operator anyway. If you want to use the is operator, you're generally testing if something is referring to something else, like list1 is list2.

If you want to define special behavior for ==, you can define __eq__ in your class definition.

like image 37
Rafe Kettler Avatar answered Oct 22 '22 04:10

Rafe Kettler