大连网站建设酷网科技,美容行业网站建设多少价格,西安网站模板建站,wordpress 301规则我有一个方法#xff0c;它有时返回一个非类型的值。那么我怎样才能质疑一个非类型的变量呢#xff1f;例如#xff0c;我需要使用if方法if not new:new #我知道这是错误的方式#xff0c;我希望你理解我的意思。我想这是在这里回答的#xff0c;显然是在以前的某个地方。…我有一个方法它有时返回一个非类型的值。那么我怎样才能质疑一个非类型的变量呢例如我需要使用if方法if not new:new #我知道这是错误的方式我希望你理解我的意思。我想这是在这里回答的显然是在以前的某个地方。如果您的方法返回的值只有bool(returnValue)等于False那么if not new:应该可以正常工作。这有时发生在内置libs中——例如re.match返回none或truthy match对象。也可以在这里看到我关于python中的null和None的答案。So how can I question a variable that is a NoneType?使用is运算符如下所示if variable is None:为什么会这样由于None是python中NoneType唯一的单例对象所以我们可以使用is操作符来检查变量中是否有None。引用is号文件The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.由于只有一个None实例因此is是检查None的首选方法。从马嘴里听到引用了python的编码风格指南-pep-008(由guido自己共同定义)。Comparisons to singletons like None should always be done with is or is not, never the equality operators.if variable is None:...if variable is not None:...根据亚历克斯·霍尔的回答也可以用isinstance来完成 NoneType type(None) x None type(x) NoneTypeTrue isinstance(x, NoneType)Trueisinstance也是直观的但其复杂之处在于它需要一条线。NoneType type(None)这对于像int和float这样的类型是不需要的。由于你不能将NoneType分为子类由于None是单体因此不应使用isinstance来检测None而应按照公认的答案进行并使用is None或is not None。不在python3.6.7上工作正如亚伦希尔的命令所指出的Since you cant subclass NoneType and since None is a singleton, isinstance should not be used to detect None - instead you should do as the accepted answer says, and use is None or is not None.原始答案然而最简单的方法是除了豆蔻的答案之外如果没有额外的行可能是isinstance(x, type(None))So how can I question a variable that is a NoneType? I need to use if method使用isinstance()不需要if语句中的isif isinstance(x, type(None)):#do stuff附加信息您还可以在一个isinstance()语句中检查多个类型如文档中所述。只需将类型编写为元组即可。isinstance(x, (type(None), bytes))由于你不能将NoneType分为子类由于None是单体因此不应使用isinstance来检测None而应按照公认的答案进行并使用is None或is not None。这个答案对python 3.6.7很有用。Python 2.7x Noneisinstance(x, type(None))或isinstance(None, type(None))真由于你不能将NoneType分为子类由于None是单体因此不应使用isinstance来检测None而应按照公认的答案进行并使用is None或is not None。哦好吧谢谢希望这个例子对您有所帮助)print(type(None) # NoneType所以您可以检查变量名的类型#Examplename 12 # name Noneif type(name) ! type(None):print(name)else:print(Cant find name)不确定这是否回答了问题。但我知道我花了一段时间才弄明白。我在浏览一个网站突然作者的名字不在了。所以需要一个支票声明。if type(author) type(None):my if bodyelse:my else body在这种情况下author可以是任何变量None可以是您要检查的任何类型。由于None是单体的所以不应使用type来检测None—而是应按照公认的答案进行并使用is None或is not None。