Python - 检查空对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20010628/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:15:28  来源:igfitidea点击:

Python - Checking for Null Object

pythonobjectnull

提问by vbiqvitovs

I'm new to Python and I don't understand how this works. I would like to assign a value to an object in Python if it is currently undefined, but when I run the if statement, it fails because the object isn't defined (Duh.).

我是 Python 新手,我不明白这是如何工作的。如果当前未定义,我想为 Python 中的对象分配一个值,但是当我运行 if 语句时,它会失败,因为该对象未定义(废话。)。

How would I fix this?

我将如何解决这个问题?

...
key = raw_input('What is your key?: ')

for i in key:
    print i
    if Count is None:
        Count = 0 

Traceback (most recent call last):
  File "Client.py", line 7, in <module>
    if Count is None:
NameError: name 'Count' is not defined
...
key = raw_input('What is your key?: ')

for i in key:
    print i
    if Count is None:
        Count = 0 

Traceback (most recent call last):
  File "Client.py", line 7, in <module>
    if Count is None:
NameError: name 'Count' is not defined

What can I do to fix this seemingly easy issue?

我能做些什么来解决这个看似简单的问题?

The above code was garbage and was something I was testing for understanding of basic Python functionality. It brought me back to the issue of assigning a value to an object which is an issue I've had before. Below is my thought process.

上面的代码是垃圾,是我为了理解基本的 Python 功能而测试的东西。它让我回到了为对象赋值的问题,这是我以前遇到的一个问题。下面是我的思考过程。

Ok, so obviously I'm not explaining something well enough here. I'm not sure what it is, but something irks me about having to assign a value to an object that is not yet relevant. For readability alone, I would like to check for a null value of an object before it is used in a statement. From what I've read below, it's going to be necessary and something I'm most likely just going to have to deal with. In my mind, this...

好吧,显然我在这里解释得不够好。我不确定它是什么,但有些事情让我感到厌烦,因为必须为尚不相关的对象分配一个值。仅为了可读性,我想在语句中使用对象之前检查对象的空值。从我在下面读到的内容来看,这将是必要的,而且我很可能只需要处理一些事情。在我看来,这...

...
object = 'ObligatoryValue'

for i in Data
    Object = Data[0] # Now the object is relevant
    ...

looks better than this...

看起来比这个更好...

...
for i in Data
    if Object is None:
        Object = Data[0] 
    ...

To even further explain the reasoning, I work in data manipulation. And the first time I ran into this issue was when I was comparing two objects. If attempted to do something like...

为了进一步解释推理,我从事数据操作。我第一次遇到这个问题是在比较两个对象时。如果试图做类似的事情......

...
Object = Line[0]
if UndefinedObject == Object
    do = 'something'
...

But I would always have an error returned because UndefinedObject was not assigned a value.

但是我总是会返回一个错误,因为 UndefinedObject 没有被赋值。

回答by Martijn Pieters

You can set Countto Noneexplicitly, first:

您可以首先明确设置CountNone

Count = None

for i in key:
   if Count is None:
       Count = 0

but in this case it would be easier to just assign 0to begin with:

但在这种情况下,只分配0开始会更容易:

Count = 0

for i in key:

回答by MrBooks

You could define it as an empty string before you can check:

您可以在检查之前将其定义为空字符串:

Count = ''

then later on you can test...

然后稍后您可以测试...

if not Count:
    Count = 0;

回答by abarnert

This is almost certainly a very bad idea. As everyone explained in comments, and Martijn Pieters's answer shows, there's a better way to do almost anything you want to do.

这几乎可以肯定是一个非常糟糕的主意。正如每个人在评论中所解释的那样,以及 Martijn Pieters 的回答表明,有一种更好的方法可以做几乎任何你想做的事情。

Also, this is not"Checking for Null Object". The "null object" is None. Martijn's answer shows how to do that. This is checking for a variable not being bound at all, not for a variable being bound to the null object.

此外,这不是“检查空对象”。“空对象”是None. Martijn 的回答展示了如何做到这一点。这是在检查一个根本没有被绑定的变量,而不是一个被绑定到空对象的变量。

Anyway, Python doesn't prevent you from doing this, it just doesn't make it easy (because it's almostalways a bad idea, but occasionally necessary).

无论如何,Python 不会阻止您这样做,它只是让它变得容易(因为它几乎总是一个坏主意,但有时是必要的)。

So, here's how to do it:

所以,这是如何做到的:

for i in key:
    try:
        Count
    except NameError:
        Count = 0

Or, if you need to know whether it exists at a particular scope—e.g., you only care if there's a globalCount, not a Countanywhere:

或者,如果您需要知道它是否存在于特定范围内——例如,您只关心是否有一个globalCount,而不是一个Count任何地方:

for i in key:
    if 'Count' not in globals():
        Count = 0

Or you can use hasattror getattron the appropriate namespace.

或者您可以在适当的命名空间上使用hasattrgetattr