如何列出一个类的所有字段(没有方法)? [英] How to list all fields of a class (and no methods)?

查看:100
本文介绍了如何列出一个类的所有字段(没有方法)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设o是一个Python对象,并且我想要o的所有字段,而没有任何方法或__stuff__.该怎么办?

Suppose o is a Python object, and I want all of the fields of o, without any methods or __stuff__. How can this be done?

我已经尝试过类似的事情:

I've tried things like:

[f for f in dir(o) if not callable(f)]

[f for f in dir(o) if not inspect.ismethod(f)]

,但是它们返回与dir(o)相同的结果,大概是因为dir提供了一个字符串列表.此外,即使我可以使用此命令,也会返回__class__之类的信息.

but these return the same as dir(o), presumably because dir gives a list of strings. Also, things like __class__ would be returned here, even if I get this to work.

推荐答案

您可以通过__dict__属性或

You can get it via the __dict__ attribute, or the built-in vars function, which is just a shortcut:

>>> class A(object):
...     foobar = 42
...     def __init__(self):
...         self.foo = 'baz'
...         self.bar = 3
...     def method(self, arg):
...         return True
...
>>> a = A()
>>> a.__dict__
{'foo': 'baz', 'bar': 3}
>>> vars(a)
{'foo': 'baz', 'bar': 3}

只有对象的属性.方法和类属性不存在.

There's only attributes of the object. Methods and class attributes aren't present.

这篇关于如何列出一个类的所有字段(没有方法)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆