推荐答案
调用函数 collections.namedtuple
会为您提供一个新类型,它是tuple
的子类(没有其他类),带有一个名为_fields
的成员,它是一个元组,其项均为字符串.因此,您可以检查以下每一项:
Calling the function collections.namedtuple
gives you a new type that's a subclass of tuple
(and no other classes) with a member named _fields
that's a tuple whose items are all strings. So you could check for each and every one of these things:
def isnamedtupleinstance(x):
t = type(x)
b = t.__bases__
if len(b) != 1 or b[0] != tuple: return False
f = getattr(t, '_fields', None)
if not isinstance(f, tuple): return False
return all(type(n)==str for n in f)
有可能从中得到误报,但前提是有人要竭尽全力地创建看起来像命名元组的 lot 但不是一个元组的类型;-)
it IS possible to get a false positive from this, but only if somebody's going out of their way to make a type that looks a lot like a named tuple but isn't one;-).
这篇关于如何检查对象是否是namedtuple的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!