如何在Python中找到对象的所有属性的类型?

2024-04-26 18:02:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有张量

x = torch.tensor([1, 2, 3])

是我干的

len(dir(x))

给了这个

464个

我想知道这464个属性中有多少是内置的函数、方法、方法或任何其他类型。你知道吗

如何列出张量的属性类型?你知道吗


Tags: 方法函数类型len属性dirtorch内置
3条回答

help(x)生成一些关于您传入内容的基本文档。它会告诉你对象的类型,属性,方法等等

通常,不应该访问的属性以___开头。所以,[att for att in dir(x) if not att.startswith('_')]

如果您也想排除函数,请将and not callable(att)添加到条件中。你知道吗

这就是我得到张量所有属性的类型

导入模块,创建张量

import torch
from collections import defaultdict

x = torch.tensor([1., 2., 3.])

下表给出了属性及其类型的列表

a = [(f'x.{i}', type(getattr(x, i))) for i in dir(x)]

使用defaultdict制作了一个字典,它根据类型存储属性。你知道吗

e = defaultdict(list)
for i, j in a.items():
  e[j].append(i)

相关问题 更多 >