明天写代码时无心碰到NotImplemented,我一愣,难道是NotImplementedError的胞弟,所以略微钻研了一下。

NotImplemented故名思议,就是“未实现”,个别是用在一些比拟算法中的,如class的\_\_eq\_\_,\_\_lt\_\_等,留神NotImplemented并不是异样,所以不能

应用raise,当没有实现时应该是return NotImplemented。

咱们能够看看django中的Field的实现,

@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

那提供NotImplemented有什么益处?益处就在于如果A == B NotImplemented,会去调用B的\_\_eq\_\_办法,如果B也没有会调用cmp办法。

咱们看上面一个例子:

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

如果你们稳固库中有这么一段代码,而且Person可能蕴含了很多字段,然而你想实现Person和整数比拟。

person=Person(10)print person == 10 #False

很遗憾,下面后果是False,不合乎咱们要求,至于为什么是10,稍后再说,咱们先看看如何解决这个问题?

其实这时你能够简略封装一个age对象,

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,很完满,那咱们从下面能失去什么论断呢?

咱们在写一些根底代码时,即便是没实现,也不要raise NotImplementedError,而是return NotImplemented,相当于提供给其它不同对象的比拟接口,这对

代码扩大十分有益处。

咱们再来看看下面那么间接和10比,为什么是False?

先看上面这段代码:

class A:    def __lt__(self, a):        return NotImplemented    def __add__(self ,a):        return NotImplementedprint A() < A() # Trueprint A() < 1  # False

很奇怪吧,明明曾经间接是 NotImplemented,为什么还有后果?
大胆猜想,后面阐明最初会应用cmp比拟,很显著当都没有定义时会比拟id值,也就是内存地址,后创立的对象内存地址大,就是这个情理。

至于A() < 1,因为python的小整数对象在初始化时创立的,内存地址必定小,如果你还不信,

不过千万别搞没有意思的操作,

这也是这位兄弟不解的中央,http://stackoverflow.com/questions/1062096/python-notimplemented-constant

本文转自 https://blog.csdn.net/yueguanghaidao/article/details/38641251?spm=1001.2014.3001.5502,如有侵权,请分割删除。