dir 内置函数将为您提供所有对象的属性,包括 __str__ , __dict__ 等特殊方法以及您可能不想要的其他一些属性 . 但你可以这样做:
>>> 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
53
我想我会花一些时间向你展示如何通过 dict(obj) 将对象翻译成dict .
class A(object):
d = '4'
e = '5'
f = '6'
def __init__(self):
self.a = '1'
self.b = '2'
self.c = '3'
def __iter__(self):
# first start by grabbing the Class items
iters = dict((x,y) for x,y in A.__dict__.items() if x[:2] != '__')
# then update the class items with the instance items
iters.update(self.__dict__)
# now 'yield' through the items
for x,y in iters.items():
yield x,y
a = A()
print(dict(a))
# prints "{'a': '1', 'c': '3', 'b': '2', 'e': '5', 'd': '4', 'f': '6'}"
10 回答
我已经结合两个答案来解决:
这会遗漏对象从其类继承的属性 . 例如,
hasattr(a,'x')为真,但'x'不出现在.__ dict__中
请注意,Python 2.7中的最佳实践是使用new-style类(Python 3不需要),即
还有,'s a difference between an ' object ' and a ' class' . 要从任意对象构建字典,使用
__dict__
就足够了 . 通常,您将在类级别声明您的方法,并在实例级别声明您的属性,因此__dict__
应该没问题 . 例如:更好的方法(由注释中的robert建议)是内置vars函数:
或者,根据您想要做的事情,从
dict
继承可能会很好 . 然后你的类已经是一个字典,如果你想要你可以覆盖getattr
和/或setattr
来调用并设置字典 . 例如:而不是
x.__dict__
,使用vars(x)
实际上更加pythonic .dir
内置函数将为您提供所有对象的属性,包括__str__
,__dict__
等特殊方法以及您可能不想要的其他一些属性 . 但你可以这样做:因此可以通过定义
props
函数将此扩展为仅返回数据属性而不是方法:我想我会花一些时间向你展示如何通过
dict(obj)
将对象翻译成dict .这段代码的关键部分是
__iter__
函数 .正如评论所解释的那样,我们要做的第一件事就是 grab Class项并防止任何以'__'开头的内容 .
一旦你创建了
dict
,那么你可以使用update
dict函数并传入实例__dict__
.这些将为您提供完整的成员类实例字典 . 现在剩下的就是迭代它们并产生回报 .
此外,如果您打算大量使用它,您可以创建一个
@iterable
类装饰器 .迟到的答案,但提供了完整性和googlers的好处:
这不会显示在类中定义的方法,但它仍将显示包括分配给lambdas的字段或以双下划线开头的字段 .
如果要列出部分属性,请覆盖
__dict__
:如果您的
instance
获取一些大块数据并且您想将d
推送到Redis之类的消息队列,这会有很大帮助 .我认为最简单的方法是为类创建 getitem 属性 . 如果需要写入对象,可以创建自定义 setattr . 以下是 getitem 的示例:
dict 将对象属性生成到字典中,字典对象可用于获取所需的项目 .
PYTHON 3:
现在您可以在自己的类中使用上面的代码: