Writing code today inadvertently encountered notimplemented, I am a leng, is notimplementederror of brother, so a little study a bit.
notimplemented Hence the name Incredibles, is "not realized", is generally used in some comparison algorithm, such as class __eq__,__lt__, pay attention to notimplemented is not abnormal, so can not
With raise, it should be return notimplemented when not implemented .
We can look at the implementation of the field in Django,
@total_orderingclass field (object): "" " Base class for all Field types" " def __eq__ (self, Other): # Needed For @total_ordering if Isinstance (Other, Field): return self.creation_counter = = Other.creation_counter return notimplemented def __lt__ (self, Other): # needed because Bisect does don't take a comparison functi On. If Isinstance (Other, Field): return Self.creation_counter < Other.creation_counter return notimplemented
What are the benefits of providing notimplemented? The advantage is that if a = = B notimplemented, the __eq__ method of B is called, and if B does not call the CMP method.
Let's take a look at the following example:
Class Person: def __init__ (self, Age): Self.age = Age def __eq__ (self, Other): if not isinstance ( Other, person): return notimplemented return self.age = = Other.age
If you have such a piece of code in your stability library, and the person may contain many fields, you want to implement person and integer comparisons.
Person=person (ten) print person = = #False
Unfortunately, the result above is false, does not meet our requirements, as to why is 10, we will say later, we first look at how to solve the problem?
In fact, you can simply encapsulate an age object,
Class Age: def __init__ (self, Age): Self.age = Age def __eq__ (self, Other): return self.age = = Other.age Person=person (age=age) print person = = Age #True
OK, perfect, so what can we get from the above?
We write some basic code, even if it is not implemented, do not raise notimplementederror, but return notimplemented, equivalent to provide to other different objects of the comparison interface, which
Code extensions are very beneficial.
Let's take a look at the above so direct and 10 ratio, why is false?
Let's look at the following code:
Class A: def __lt__ (Self, a): return notimplemented def __add__ (Self, a): return Notimplementedprint A () < A () # Trueprint A () < 1 # False
It's strange, obviously, it's straight.notimplemented, why is there a result?
Bold guess, the previous description will use CMP comparison, it is obvious that when there is no definition will compare the ID value, that is, memory address, after the creation of the object memory address large, this is the truth.
As for A () < 1, because Python's small integer object was created at initialization, the memory address is definitely small, if you don't believe it,
But don't do anything interesting,
This is where the brother is puzzled, http://stackoverflow.com/questions/1062096/python-notimplemented-constant.