无 Python 错误/错误? [英] None Python error/bug?

查看:50
本文介绍了无 Python 错误/错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,你有 None 单例,它在某些情况下表现得很奇怪:

<预><代码>>>>a = 无>>>类型(一)<输入'NoneType'>>>>isinstance(a,None)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,位于 <module>类型错误:isinstance() arg 2 必须是类、类型或类和类型的元组

所以首先, 显示 None 不是类型,但 NoneType 是.然而,当您运行 isinstance(a,NoneType) 时,它会响应一个错误:NameError: name 'NoneType' is not defined

现在,鉴于此,如果您有一个输入默认设置为 None 的函数,并且需要检查,您可以执行以下操作:

如果变量是无:#做一点事别的:#做一点事

我不能执行以下操作的原因是什么:

if isinstance(variable,None): #or NoneType#做一点事别的:#做一点事

我只是想找一个详细的解释,这样我才能更好地理解这一点

很好的应用

假设我想使用 isinstance 以便在 variable 是多种类型(包括 None)时我可以做一些事情:>

if isinstance(variable,(None,str,float)):#做一点事

解决方案

你可以试试:

<预><代码>>>>变量 = 无>>>isinstance(变量,类型(无))真的>>>变量 = 真>>>isinstance(变量,类型(无))错误的

isinstance 接受 2 个参数 isinstance(object, classinfo) 在这里,通过传递 None 您将 classinfo 设置为 None,因此出现错误.您需要传入类型.

In Python you have the None singleton, which acts pretty oddly in certain circumstances:

>>> a = None
>>> type(a)
<type 'NoneType'>
>>> isinstance(a,None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

So first off, <type 'NoneType'> displays that None is not a type, but that NoneType is. Yet when you run isinstance(a,NoneType), it responds with an error: NameError: name 'NoneType' is not defined

Now, given this, if you have a function with an input default set to None, and need to check, you would do the following:

if variable is None:
    #do something
else:
    #do something

what is the reason that I cannot do the following instead:

if isinstance(variable,None): #or NoneType
    #do something
else:
    #do something

I am just looking for a detailed explanation so I can better understand this

Edit: good application

Lets say I wanted to use isinstance so that I can do something if variable is a variety of types, including None:

if isinstance(variable,(None,str,float)):
    #do something

解决方案

You can try:

>>> variable = None
>>> isinstance(variable,type(None))
True
>>> variable = True
>>> isinstance(variable,type(None))
False

isinstance takes 2 arguments isinstance(object, classinfo) Here, by passing None you are setting classinfo to None, hence the error. You need pass in the type.

这篇关于无 Python 错误/错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆