在Python中引用空对象

在Python中引用空对象,python,null,Python,Null,在Python中如何引用null对象?在Python中,“null”对象是singletonNone 检查事物是否“无”的最佳方法是使用标识运算符,is: if foo is None: ... 它不像在其他语言中那样被称为null,但是。此对象始终只有一个实例,因此如果需要,可以检查与x is None(标识比较)的等价性,而不是x==None。在Python中,为了表示没有值,可以对对象使用None值(types.NoneType.None),对字符串使用“”(或len()==0)

在Python中如何引用null对象?

在Python中,“null”对象是singleton
None

检查事物是否“无”的最佳方法是使用标识运算符,
is

if foo is None:
    ...

它不像在其他语言中那样被称为null,但是。此对象始终只有一个实例,因此如果需要,可以检查与
x is None
(标识比较)的等价性,而不是
x==None

在Python中,为了表示没有值,可以对对象使用None值(types.NoneType.None),对字符串使用“”(或len()==0)。因此:

if yourObject is None:  # if yourObject == None:
    ...

if yourString == "":  # if yourString.len() == 0:
    ...
关于“==”和“is”之间的差异,使用“==”测试对象标识就足够了。然而,由于操作“is”被定义为对象标识操作,因此使用它可能比使用“==”更正确。不确定是否有速度差

无论如何,您可以看看:

  • Python文档页面
  • Python文档页面
Per,“None”直接测试为FALSE,因此最简单的表达式就足够了:

if not foo:
None
,Python的空值? Python中没有
null
;而是有
。如前所述,测试某个值是否为
None
的最准确方法是使用
is
identity操作符,该操作符测试两个变量是否引用同一对象

>>> foo is None
True
>>> foo = 'bar'
>>> foo is None
False
>>> NoneType = type(None)
>>> id(None)
10748000
>>> my_none = NoneType()
>>> id(my_none)
10748000
>>> another_none = NoneType()
>>> id(another_none)
10748000
>>> def function_that_does_nothing(): pass
>>> return_value = function_that_does_nothing()
>>> id(return_value)
10748000
基础 存在且只能有一个
None
None
是类
NoneType
的唯一实例,任何进一步实例化该类的尝试都将返回相同的对象,这使得
None
成为单例。Python新手经常看到提到
NoneType
的错误消息,并想知道它是什么。我个人的观点是,这些信息可以简单地按名称提及
None
,因为我们很快就会看到,
None
几乎没有模棱两可的余地。因此,如果您看到一些
TypeError
消息提到
NoneType
不能做这件事或不能做那件事,只需知道它只是一个
None
以它不能做的方式被使用

另外,
None
是一个内置常量。一旦启动Python,它就可以在任何地方使用,无论是在模块、类还是函数中
NoneType
相反,您需要首先通过查询其类的
None
来获取对它的引用

>>> NoneType
NameError: name 'NoneType' is not defined
>>> type(None)
NoneType
您可以使用Python的标识函数
id()
检查
None
的唯一性。它返回分配给对象的唯一编号,每个对象有一个。如果两个变量的id相同,那么它们实际上指向同一个对象

>>> foo is None
True
>>> foo = 'bar'
>>> foo is None
False
>>> NoneType = type(None)
>>> id(None)
10748000
>>> my_none = NoneType()
>>> id(my_none)
10748000
>>> another_none = NoneType()
>>> id(another_none)
10748000
>>> def function_that_does_nothing(): pass
>>> return_value = function_that_does_nothing()
>>> id(return_value)
10748000
None
不能被覆盖 在更早的Python版本(2.4之前)中,可以重新分配
None
,但不能再分配了。甚至不是作为类属性或函数的限制

# In Python 2.7
>>> class SomeClass(object):
...     def my_fnc(self):
...             self.None = 'foo'
SyntaxError: cannot assign to None
>>> def my_fnc():
        None = 'foo'
SyntaxError: cannot assign to None

# In Python 3.5
>>> class SomeClass:
...     def my_fnc(self):
...             self.None = 'foo'
SyntaxError: invalid syntax
>>> def my_fnc():
        None = 'foo'
SyntaxError: cannot assign to keyword
因此,可以安全地假设所有
None
引用都是相同的。没有任何“自定义”

要测试
None
,请使用
is
运算符 在编写代码时,您可能会尝试进行如下测试:

if value==None:
    pass
或者是为了检验这样的谎言

if not value:
    pass
value.__eq__(None)
你需要理解其中的含义,以及为什么明确表达往往是个好主意

案例1:测试值是否为
None
为什么

value is None
而不是

value==None
?

第一个相当于:

id(value)==id(None)
而表达式
value==None
实际上是这样应用的

if not value:
    pass
value.__eq__(None)
如果值真的是
None
,那么您将得到您所期望的结果

>>> nothing = function_that_does_nothing()
>>> nothing.__eq__(None)
True
在大多数情况下,结果都是一样的,但是
\uuuu eq\uuu()
方法打开了一扇门,使任何准确性保证无效,因为它可以在类中重写以提供特殊行为

以这个类为例

>>> class Empty(object):
...     def __eq__(self, other):
...         return not other
因此,您可以在
None
上试用它,它可以正常工作

>>> empty = Empty()
>>> empty==None
True
但它也适用于空字符串

>>> empty==''
True
然而

>>> ''==None
False
>>> empty is None
False
案例2:使用
None
作为布尔值 以下两个测试

if value:
    # Do something

if not value:
    # Do something
实际上被评估为

if bool(value):
    # Do something

if not bool(value):
    # Do something
None
是“False”,这意味着如果转换为布尔值,它将返回
False
,如果应用
not
运算符,它将返回
True
。但是请注意,它不是
None
所独有的属性。除了
False
本身之外,空列表、元组、集合、dict、字符串以及0以及实现
bool\uuu()返回
False
的神奇方法的类中的所有对象都共享该属性

>>> bool(None)
False
>>> not None
True

>>> bool([])
False
>>> not []
True

>>> class MyFalsey(object):
...     def __bool__(self):
...         return False
>>> f = MyFalsey()
>>> bool(f)
False
>>> not f
True
因此,当以以下方式测试变量时,请特别注意测试中包含或排除的内容:

def some_function(value=None):
    if not value:
        value = init_value()
在上面的例子中,您的意思是当值专门设置为
None
时调用
init_value()
,还是说设置为
0
的值、空字符串或空列表也应触发初始化?就像我说的,要留心。通常情况下,在Python中显式优于隐式

None
在实践中
None
用作信号值
None
在Python中具有特殊状态。它是最受欢迎的基线值,因为许多算法将其视为例外值。在这种情况下,它可以用作标志,表示条件需要一些特殊处理(例如设置默认值)

您可以将
None
分配给函数的关键字参数,然后显式测试它

def my_function(value, param=None):
    if param is None:
        # Do something outrageous!
您可以在尝试获取对象的属性时将其作为默认值返回,然后在执行特殊操作之前显式测试它

value = getattr(some_obj, 'some_attribute', None)
if value is None:
    # do something spectacular!
默认情况下,当尝试访问不存在的密钥时,字典的
get()
方法返回
None

>>> some_dict = {}
>>> value = some_dict.get('foo')
>>> value is None
True
如果您试图使用下标符号a
KeyError
wou访问它
try:
    value = some_dict['some_key']
    if value is None:
        # Do something here because 'some_key' is set to None
except KeyError:
    # Set a default
    value = None
    # And do something because 'some_key' was missing
    # from the dict.
    log_something(some_dict)
def my_function(**kwargs):
    try:
        value = kwargs['some_key']
        if value is None:
            # Do something because 'some_key' is explicitly
            # set to None
    except KeyError:
        # We assign the default
        value = None
        # And since it's not coming from the caller.
        log_something('did not receive "some_key"')
undefined = object()
def my_function(value, param1=undefined, param2=undefined):
    if param1 is undefined:
        # We know nothing was passed to it, not even None
        log_something('param1 was missing')
        param1 = None


    if param2 is undefined:
        # We got nothing here either
        log_something('param2 was missing')
        param2 = None
value = some_dict.get('some_key', undefined)
if value is None:
    log_something("'some_key' was set to None")

if value is undefined:
    # We know that the dict didn't have 'some_key'
    log_something("'some_key' was not set at all")
    value = None
value = getattr(obj, 'some_attribute', undefined)
if value is None:
    log_something("'obj.some_attribute' was set to None")
if value is undefined:
    # We know that there's no obj.some_attribute
    log_something("no 'some_attribute' set on obj")
    value = None
>>>type(None)
<class 'NoneType'>
>>>variable = None
>>>variable is None
True
year=None
year_val= 'null' if year is None else  str(year)
print(f'{year_val}')

null