Python 什么是 None 值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19473185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a None value?
提问by The_Diver
I have been studying Python, and I read a chapter which describes the None
value, but unfortunately this book isn't very clear at some points. I thought that I would find the answer to my question, if I share it there.
我一直在研究 Python,我读过一章描述了它的None
价值,但不幸的是,这本书在某些方面不是很清楚。我想我会找到我的问题的答案,如果我在那里分享它。
I want to know what the None
value isand what do you use it for?
我想知道None
价值是什么,你用它做什么?
And also, I don't get this part of the book:
而且,我不明白这本书的这一部分:
Assigning a value of
None
to a variable is one way to reset it to its original, empty state.
分配的值
None
给变量是将其重置到其原始的,空的状态的一种方法。
What does that mean?
这意味着什么?
The answers were great, although I didn't understand most of answers due to my low knowledge of the computer world (I haven't learned about classes, objects, etc.). What does this sentence mean?
答案很棒,尽管由于我对计算机世界的了解不足(我还没有了解类、对象等),我无法理解大部分答案。这句话是什么意思?
Assigning a value of
None
to a variable is one way to reset it to its original, empty state.
分配的值
None
给变量是将其重置到其原始的,空的状态的一种方法。
Final:
最终的:
Finally I've got my answer from looking to different answers. I must appreciate all the people who put their times to help me (especially Martijn Pieters and DSM), and I wish that I could choose all answers as the best, but the selection is limited to one. All of the answers were great.
最后,我从寻找不同的答案中得到了答案。我必须感谢所有花时间帮助我的人(尤其是 Martijn Pieters 和 DSM),我希望我可以选择所有答案为最佳,但只能选择一个。所有的答案都很棒。
采纳答案by DSM
Martijn's answer explains what None
is in Python, and correctly states that the book is misleading. Since Python programmers as a rule would never say
Martijn 的回答解释了None
Python 中的内容,并正确地指出这本书具有误导性。因为 Python 程序员通常永远不会说
Assigning a value of
None
to a variable is one way to reset it to its original, empty state.
分配的值
None
给变量是将其重置到其原始的,空的状态的一种方法。
it's hard to explain what Briggs means in a way which makes sense and explains why no one here seems happy with it. One analogy which may help:
很难以一种有意义的方式解释布里格斯的意思,并解释为什么这里似乎没有人对此感到满意。一个可能有帮助的类比:
In Python, variable names are like stickers put on objects. Every sticker has a unique name written on it, and it can only be on one object at a time, but you could put more than one sticker on the same object, if you wanted to. When you write
在 Python 中,变量名就像贴在对象上的贴纸。每个贴纸上都写有唯一的名称,一次只能贴在一个物体上,但如果您愿意,您可以在同一个物体上放置多个贴纸。当你写
F = "fork"
you put the sticker "F" on a string object "fork"
. If you then write
你把贴纸“F”放在一个字符串对象上"fork"
。如果你然后写
F = None
you move the sticker to the None
object.
你将贴纸移到None
物体上。
What Briggs is asking you to imagine is that you didn't writethe sticker "F"
, there was alreadyan F
sticker on the None
, and all you did was moveit, from None
to "fork"
. So when you type F = None
, you're "reset[ting] it to its original, empty state", if we decided to treat None
as meaning empty state
.
Briggs 让你想象的是,你没有写贴纸"F"
,上面已经有F
贴纸了None
,你所做的只是将它从None
到移动"fork"
。因此,当您键入 时F = None
,如果我们决定将其None
视为 含义,您就是在“将其重置为原始的空状态” empty state
。
I can see what he's getting at, but that's a bad way to look at it. If you start Python and type print(F)
, you see
我可以看到他在说什么,但这是一种不好的看待方式。如果您启动 Python 并键入print(F)
,您会看到
>>> print(F)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'F' is not defined
and that NameError
means Python doesn't recognize the name F
, because there is no such sticker. If Briggs were right and F = None
resets F
to its original state, then it should be there now, and we should see
这NameError
意味着 Python 无法识别名称F
,因为没有这样的贴纸。如果 Briggs 是对的并F = None
重置F
为原始状态,那么它现在应该在那里,我们应该看到
>>> print(F)
None
like we do after we type F = None
and put the sticker on None
.
就像我们在打字F = None
并贴上贴纸后所做的那样None
。
So that's all that's going on. In reality, Python comes with some stickers already attached to objects (built-in names), but others you have to write yourself with lines like F = "fork"
and A = 2
and c17 = 3.14
, and then you can stick them on other objects later (like F = 10
or F = None
; it's all the same.)
这就是正在发生的一切。实际上,Python 附带了一些已经贴在对象上的贴纸(内置名称),但其他一些你必须自己用F = "fork"
和A = 2
和这样的行来写c17 = 3.14
,然后你可以稍后将它们贴在其他对象上(比如F = 10
或F = None
; 都是一样的.)
Briggs is pretending that all possible stickers you might want to write were already stuck to the None
object.
Briggs 假装你可能想写的所有可能的贴纸都已经粘在了None
物体上。
回答by Martijn Pieters
None
is just a value that commonly is used to signify 'empty', or 'no value here'. It is a signal object; it only has meaning because the Python documentation says it has that meaning.
None
只是一个通常用于表示“空”或“此处无值”的值。它是一个信号对象;它只有意义,因为 Python 文档说它有这个意义。
There is only one copy of that object in a given Python interpreter session.
在给定的 Python 解释器会话中只有该对象的一个副本。
If you write a function, and that function doesn't use an explicit return
statement, None
is returned instead, for example. That way, programming with functions is much simplified; a function alwaysreturns something, even if it is only that one None
object.
例如,如果您编写一个函数,并且该函数不使用显式return
语句,None
则返回。这样,函数编程就大大简化了;一个函数总是返回一些东西,即使它只是一个None
对象。
You can test for it explicitly:
您可以明确地测试它:
if foo is None:
# foo is set to None
if bar is not None:
# bar is set to something *other* than None
Another use is to give optional parameters to functions an 'empty' default:
另一个用途是为函数提供一个“空”默认值的可选参数:
def spam(foo=None):
if foo is not None:
# foo was specified, do something clever!
The function spam()
has a optional argument; if you call spam()
without specifying it, the default value None
is given to it, making it easy to detect if the function was called with an argument or not.
该函数spam()
有一个可选参数;如果调用时spam()
未指定,则会为其提供默认值None
,以便轻松检测是否使用参数调用该函数。
Other languages have similar concepts. SQL has NULL
; JavaScript has undefined
andnull
, etc.
其他语言也有类似的概念。SQL有NULL
; JavaScript 有undefined
和null
等。
Note that in Python, variables exist by virtue of being used. You don't need to declare a variable first, so there are no really emptyvariables in Python. Setting a variable to None
is then not the same thing as setting it to a default empty value; None
is a value too, albeit one that is often used to signalemptyness. The book you are reading is misleading on that point.
请注意,在 Python 中,变量是因为被使用而存在的。你不需要先声明一个变量,所以Python中没有真正的空变量。将变量设置None
为与将其设置为默认空值不同;None
也是一个值,尽管它经常被用来表示空虚。您正在阅读的书在这一点上具有误导性。
回答by Azeirah
I love code examples (as well as fruit), so let me show you
我喜欢代码示例(以及水果),所以让我向您展示
apple = "apple"
print(apple)
>>> apple
apple = None
print(apple)
>>> None
None means nothing, it has no value.
None 没有任何意义,它没有任何价值。
None evaluates to False.
None 评估为 False。
回答by thefourtheye
This is what the Python documentationhas got to say about None
:
这就是Python 文档不得不说的内容None
:
The sole value of types.NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function.
Changed in version 2.4: Assignments to None are illegal and raise a SyntaxError.
Note The names None and debugcannot be reassigned (assignments to them, even as an attribute name, raise SyntaxError), so they can be considered “true” constants.
types.NoneType 的唯一值。None 经常用于表示没有值,就像默认参数没有传递给函数一样。
在 2.4 版更改:对 None 的赋值是非法的,并会引发 SyntaxError。
注意名称 None 和debug不能重新分配(分配给它们,即使作为属性名称,也会引发 SyntaxError),因此它们可以被视为“真”常量。
Let's confirm the type of
None
firstprint type(None) print None.__class__
Output
<type 'NoneType'> <type 'NoneType'>
让我们
None
先确认一下类型print type(None) print None.__class__
输出
<type 'NoneType'> <type 'NoneType'>
Basically, NoneType
is a data type just like int
, float
, etc. You can check out the list of default types available in Python in 8.15. types — Names for built-in types.
基本上,NoneType
是一种类似于int
、float
等的数据类型。您可以查看 Python 8.15 中可用的默认类型列表。类型 - 内置类型的名称。
And,
None
is an instance ofNoneType
class. So we might want to create instances ofNone
ourselves. Let's try thatprint types.IntType() print types.NoneType()
Output
0 TypeError: cannot create 'NoneType' instances
并且,
None
是NoneType
类的一个实例。所以我们可能想要创建None
自己的实例。让我们试试看print types.IntType() print types.NoneType()
输出
0 TypeError: cannot create 'NoneType' instances
So clearly, cannot create NoneType
instances. We don't have to worry about the uniqueness of the value None
.
很明显,不能创建NoneType
实例。我们不必担心 value 的唯一性None
。
Let's check how we have implemented
None
internally.print dir(None)
Output
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
让我们检查一下我们是如何在
None
内部实施的。print dir(None)
输出
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
Except __setattr__
, all others are read-only attributes. So, there is no way we can alter the attributes of None
.
除了__setattr__
,所有其他属性都是只读属性。因此,我们无法更改None
.
Let's try and add new attributes to
None
setattr(types.NoneType, 'somefield', 'somevalue') setattr(None, 'somefield', 'somevalue') None.somefield = 'somevalue'
Output
TypeError: can't set attributes of built-in/extension type 'NoneType' AttributeError: 'NoneType' object has no attribute 'somefield' AttributeError: 'NoneType' object has no attribute 'somefield'
让我们尝试添加新属性
None
setattr(types.NoneType, 'somefield', 'somevalue') setattr(None, 'somefield', 'somevalue') None.somefield = 'somevalue'
输出
TypeError: can't set attributes of built-in/extension type 'NoneType' AttributeError: 'NoneType' object has no attribute 'somefield' AttributeError: 'NoneType' object has no attribute 'somefield'
The above seen statements produce these error messages, respectively. It means that, we cannot create attributes dynamically on a None
instance.
上面看到的语句分别产生这些错误消息。这意味着,我们不能在None
实例上动态创建属性。
Let us check what happens when we assign something
None
. As per the documentation, it should throw aSyntaxError
. It means, if we assign something toNone
, the program will not be executed at all.None = 1
Output
SyntaxError: cannot assign to None
让我们检查一下当我们分配一些东西时会发生什么
None
。根据文档,它应该抛出一个SyntaxError
. 这意味着,如果我们为 分配一些东西None
,程序将根本不会执行。None = 1
输出
SyntaxError: cannot assign to None
We have established that
我们已经确定
None
is an instance ofNoneType
None
cannot have new attributes- Existing attributes of
None
cannot be changed. - We cannot create other instances of
NoneType
- We cannot even change the reference to
None
by assigning values to it.
None
是一个实例NoneType
None
不能有新属性- 的现有属性
None
无法更改。 - 我们不能创建其他实例
NoneType
- 我们甚至不能通过
None
给它赋值来改变对它的引用。
So, as mentioned in the documentation, None
can really be considered as a true constant
.
因此,如文档中所述,None
确实可以将其视为true constant
.
Happy knowing None
:)
很高兴知道None
:)
回答by kojiro
The bookyou refer to is clearly trying to greatlysimplify the meaning of None
. Python variables don't havean initial, empty state –?Python variables are bound (only) when they're defined. You can't create a Python variable without giving it a value.
你所指的这本书显然试图大大简化None
. Python的变量不具备初始,空状态? - Python的变量绑定(只),他们定义的时候。你不能在不给它一个值的情况下创建一个 Python 变量。
>>> print(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> def test(x):
... print(x)
...
>>> test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test() takes exactly 1 argument (0 given)
>>> def test():
... print(x)
...
>>> test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in test
NameError: global name 'x' is not defined
but sometimes you want to make a function mean different things depending on whether a variable is defined or not. You can create an argument with a default value of None
:
但有时你想让一个函数根据一个变量是否被定义而具有不同的含义。您可以创建一个默认值为 的参数None
:
>>> def test(x=None):
... if x is None:
... print('no x here')
... else:
... print(x)
...
>>> test()
no x here
>>> test('x!')
x!
The fact that this value is the special None
value is not terribly important in this case. I could've used any default value:
None
在这种情况下,该值是特殊值这一事实并不是非常重要。我可以使用任何默认值:
>>> def test(x=-1):
... if x == -1:
... print('no x here')
... else:
... print(x)
...
>>> test()
no x here
>>> test('x!')
x!
…but having None
around gives us two benefits:
……但在None
身边给我们带来两个好处:
- We don't have to pick a special value like
-1
whose meaning is unclear, and - Our function may actually need to handle
-1
as a normal input.
- 我们不必选择一个特殊值,例如
-1
其含义不清楚,并且 - 我们的函数实际上可能需要
-1
作为普通输入来处理。
>>> test(-1)
no x here
oops!
哎呀!
So the book is a little misleading mostly in its use of the word reset–?assigning None
to a name is a signal to a programmer that that value isn't being used or that the function should behave in some default way, but to reseta value to its original, undefined state you must use the del
keyword:
所以,这本书是有点误导主要集中在其使用这个词的复位-分配None
到一个名字是一个信号,一个程序员一个没有被使用的值或函数应该表现在一些默认的方式,而是要重新设置一个value 到其原始的未定义状态,您必须使用del
关键字:
>>> x = 3
>>> x
3
>>> del x
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
回答by GrvTyagi
None is a singleton object (meaning there is only one None), used in many places in the language and library to represent the absence of some other value.
None 是一个单例对象(意味着只有一个 None),在语言和库中的许多地方使用,表示没有其他值。
For example:
if d
is a dictionary, d.get(k)
will return d[k]
if it exists, but None
if d
has no key k
.
例如:
ifd
是字典,如果存在d.get(k)
则返回d[k]
,但None
如果d
没有 key k
。
Read this info from a great blog: http://python-history.blogspot.in/
从一个很棒的博客中阅读此信息:http: //python-history.blogspot.in/
回答by Sree Latha
largest=none
smallest =none
While True :
num =raw_input ('enter a number ')
if num =="done ": break
try :
inp =int (inp)
except:
Print'Invalid input'
if largest is none :
largest=inp
elif inp>largest:
largest =none
print 'maximum', largest
if smallest is none:
smallest =none
elif inp<smallest :
smallest =inp
print 'minimum', smallest
print 'maximum, minimum, largest, smallest
回答by Jadav Bheda
Other answers have already explained meaning of Nonebeautifully. However, I would still like to throw more light on this using an example.
其他答案已经很好地解释了None 的含义。但是,我仍然想通过一个例子对此进行更多说明。
Example:
例子:
def extendList(val, list=[]):
list.append(val)
return list
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
Now try to guess output of above list. Well, the answeris surprisingly as below:
现在尝试猜测上面列表的输出。好吧,答案令人惊讶如下:
list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']
But Why?
但为什么?
Many will mistakenly expect list1to be equal to [10]and list3to be equal to ['a'], thinking that the list argument will be set to its default value of []each time extendList is called.
许多人会错误地认为list1等于[10]并且list3等于['a'],认为每次调用 extendList 时,list 参数都会设置为其默认值[]。
However, what actually happens is that the new default list is created only once when the function is defined, and that same list is then used subsequently whenever extendList is invoked without a list argument being specified. This is because expressions in default arguments are calculated when the function is defined, not when it's called.
然而,实际发生的情况是,新的默认列表只在定义函数时创建一次,然后在没有指定列表参数的情况下调用 extendList 时,随后会使用相同的列表。这是因为默认参数中的表达式是在定义函数时计算的,而不是在调用时计算的。
list1and list3are therefore operating on the same default list, whereas list2is operating on a separate list that it created (by passing its own empty list as the value for the list parameter).
因此,list1和list3在同一个默认列表上运行,而list2在它创建的单独列表上运行(通过传递自己的空列表作为 list 参数的值)。
'None' the savior: (Modify example above to produce desired behavior)
“无”救世主:(修改上面的示例以产生所需的行为)
def extendList(val, list=None):
if list is None:
list = []
list.append(val)
return list
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
With this revised implementation, the output would be:
通过这个修订后的实施,输出将是:
list1 = [10]
list2 = [123]
list3 = ['a']
Note- Example credit to toptal.com
注意- toptal.com 的示例信用
回答by Dab Brill
All of these are good answers but I think there's more to explain why None
is useful.
所有这些都是很好的答案,但我认为还有更多内容可以解释为什么None
有用。
Imagine you collecting RSVPs to a wedding. You want to record whether each person will attend. If they are attending, you set person.attending = True
. If they are not attending you set person.attending = False
. If you have not received any RSVP, then person.attending = None
. That way you can distinguish between no information - None
- and a negative answer.
想象一下,您正在为婚礼收集回复。您想记录每个人是否会参加。如果他们参加,你设置person.attending = True
。如果他们不参加你设置person.attending = False
。如果您还没有收到任何回复,那么person.attending = None
. 这样你就可以区分没有信息 - None
- 和否定答案。