The beauty of Python [from cainiao to masters] -- NotImplemented Analysis

Source: Internet
Author: User

The beauty of Python [from cainiao to masters] -- NotImplemented Analysis

I did not have the intention to encounter NotImplemented when I wrote the code today. I was wondering if it was the younger brother of NotImplementedError, so I did a little research.

NotImplemented is called "not implemented". It is generally used in some comparative algorithms, such as _ eq __,__ lt _ of the class. Note that NotImplemented is not an exception, so no

When raise is used, return NotImplemented should be used when not implemented.

Let's look at the implementation of 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):        # This is needed because bisect does not take a comparison function.        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 will be called. If B does not, the cmp method will be called.

Let's 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 the stable library and the Person may contain many fields, you want to compare the Person with the integer.

person=Person(10)print person == 10 #False
Unfortunately, the above result is False, which does not meet our requirements. As for why 10, let's talk about it later. Let's first look at how to solve this 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(10)age=Age(10)print person == age #True
OK. It's perfect. So what can we draw from the above conclusions?

When writing some basic code, do not raise NotImplementedError even if it is not implemented, but return NotImplemented, which is equivalent to a comparison interface provided to other different objects.

Code extension is very beneficial.


Let's take a look at the above comparison with 10. Why is it False?

Let's take a 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. It's already known as NotImplemented. Why are there any results?
Bold speculation, the above description will use cmp comparison at the end, it is obvious that when there is no definition, it will compare the id value, that is, the memory address, the memory address of the created object is large, that is, this principle.

As for A () <1, because the small integer object of python is created during initialization, the memory address must be small. If you do not believe it,


However, do not perform meaningless operations, <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD48cD48aW1nIHNyYz0 = "http://www.2cto.com/uploadfile/Collfiles/20140818/20140818085156256.jpg" alt = ""/>

This is what this brothers don't understand, http://stackoverflow.com/questions/1062096/python-notimplemented-constant.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.