Ale*_*lli 39
调用该函数 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)
Run Code Online (Sandbox Code Playgroud)
有可能得到这样的假阳性,但只有当有人在走出去的方式,使一个类型,看起来很多像一个名为元组,但不是一个;-).
Mat*_*ice 20
我意识到这是旧的,但我觉得这很有用:
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
Run Code Online (Sandbox Code Playgroud)
tec*_*kuz 10
3.7+
def isinstance_namedtuple(obj) -> bool:
return (
isinstance(obj, tuple) and
hasattr(obj, '_asdict') and
hasattr(obj, '_fields')
)
Run Code Online (Sandbox Code Playgroud)