>>> class Foo(object):
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> [name for name in dir(f) if not name.startswith('__')]
[ 'bar', 'baz' ]
>>> dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__'))
{ 'bar': 'hello', 'baz': 'world' }
因此,可以通过定义如下的props函数,将其扩展为仅返回数据属性而不是方法:
import inspect
def props(obj):
pr = {}
for name in dir(obj):
value = getattr(obj, name)
if not name.startswith('__') and not inspect.ismethod(value):
pr[name] = value
return pr
注意,Python2.7中的最佳实践是使用new-style类(Python3不需要)
而且,对象和类之间也有区别。要从任意对象构建字典,只需使用
__dict__
。通常,您将在类级别声明方法,在实例级别声明属性,因此__dict__
应该没问题。例如:更好的方法(由注释中的robert建议)是内置的^{} 函数:
或者,取决于你想做什么,从
dict
继承可能会更好。那么您的类已经是字典了,如果您想重写getattr
和/或setattr
来调用并设置dict实际上,使用
vars(x)
比使用x.__dict__
更像是Python。内置的
dir
将为您提供对象的所有属性,包括__str__
、__dict__
等特殊方法,以及其他一些您可能不需要的方法。但你可以这样做:因此,可以通过定义如下的
props
函数,将其扩展为仅返回数据属性而不是方法:相关问题 更多 >
编程相关推荐