如何检查,如果对象是一个实例namedtuple?
-
24-09-2019 - |
题
我怎么检查的对象是一个实例 叫元组?
解决方案
叫 功能 collections.namedtuple
给你一个新的类型的一类 tuple
(并且没有其他类别)的一个成员命名的 _fields
那是一组的物品都是有弦。所以你可以检查每一个这些事情:
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)
它是可能得到一个虚假的积极从这个,但只有如果有人出去他们的方式做一个类型,看起来一个 很多 像一个名为tuple但不是其中之一;-).
其他提示
我意识到这是旧的,但是我发现这很有用:
from collections import namedtuple
SomeThing = namedtuple('SomeThing', 'prop another_prop')
SomeOtherThing = namedtuple('SomeOtherThing', 'prop still_another_prop')
a = SomeThing(1, 2)
isinstance(a, SomeThing) # True
isinstance(a, SomeOtherThing) # False
如果你需要检查之前的呼叫namedtuple特定的功能,那么只要打电话给他们,赶上的例外,而不是。这是首选的方式做到这一点在蟒蛇。
改善什么Lutz发表:
def isinstance_namedtuple(x):
return (isinstance(x, tuple) and
isinstance(getattr(x, '__dict__', None), collections.Mapping) and
getattr(x, '_fields', None) is not None)
我用
isinstance(x, tuple) and isinstance(x.__dict__, collections.abc.Mapping)
这对我来说似乎最好地反映词典方面性质的命名元组。它的出现强劲反对一些可以想象将来的变化也可能还会的工作与许多第三方namedtuple上下班,如果发生这样的事情存在。
不隶属于 StackOverflow