16

I would like to create a class that inherites from None.

Tried this:

class InvalidKeyNone(None):
    pass

but that gives me:

TypeError: Error when calling the metaclass bases
    cannot create 'NoneType' instances

What would be the correct solution that gives me a type that behaves exactly like None but which I can type test?

foo = InvalidKeyNone()
print(type(foo))
>>> InvalidKeyNone

[EDIT]

I want to do this because I am creating a selection scheme on Python datastructures:

bar = select(".foo.bar.[1].x", {"foo":{"bar":[{"x":1}, {"x":2}], "baz":3})
print(bar)
>> 2

And I want to be able to determine whether I get a None because the selected value is None or because the key was not found. HOWEVER it must return a (ducktyped) None that behaves exactly like a None. No exceptions or custom type returning here.

[EDIT]

Ok, so the consensus is: can't be done. Which although unsatisfactory is a valid answer. Since I really want the default behavior to have it return a None when the key is not present I think I will have the select eat a param to switch to exception throwing when appropriate. Thanks.

4

3 回答 3

18

None是一个常数types.NoneType,是(对于v2.7,对于v3.x)的唯一值

无论如何,当你尝试继承自types.NoneType

from types import NoneType

class InvalidKeyNone(NoneType):
    pass

foo = InvalidKeyNone()
print(type(foo))

你会得到这个错误

蟒蛇2

TypeError:调用元类基类型“NoneType”时出错不是可接受的基类型

蟒蛇 3

ImportError:无法导入名称“NoneType”

简而言之,你不能继承自NoneType

无论如何,为什么要一个类继承NoneType

于 2013-07-02T11:42:58.483 回答
13

子类化 None 没有意义,因为它是一个单例并且只能有一个。你说你想要一个具有相同行为的类,但 None 没有任何行为!

如果您真正想要的是一个唯一的占位符,您可以从函数返回以指示特殊情况,那么最简单的方法是创建一个唯一的对象实例:

InvalidKey = object()

result = doSomething()
if result is InvalidKey:
    ...
于 2013-07-02T11:46:51.140 回答
3

没有办法做到这一点,至少在你做了一些无法理解的黑魔法之前绝对不会。

您可能应该使用异常。

于 2013-07-02T11:44:38.473 回答