您知道是否有一个内置函数可以从任意对象构建字典吗?我想这样做:
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
注意:它不应该包括方法。只有字段。
您知道是否有一个内置函数可以从任意对象构建字典吗?我想这样做:
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
注意:它不应该包括方法。只有字段。
当前回答
我想我应该花点时间向您展示如何通过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'}"
这段代码的关键部分是__iter__函数。
正如注释所解释的,我们要做的第一件事是抓取Class项,并防止任何以'__'开头的内容。
一旦创建了字典,就可以使用update dict函数并传入实例__dict__。
这将为您提供一个完整的类+实例成员字典。现在剩下的就是遍历它们并产生返回值。
另外,如果你计划经常使用这个,你可以创建一个@iterable类装饰器。
def iterable(cls):
def iterfn(self):
iters = dict((x,y) for x,y in cls.__dict__.items() if x[:2] != '__')
iters.update(self.__dict__)
for x,y in iters.items():
yield x,y
cls.__iter__ = iterfn
return cls
@iterable
class B(object):
d = 'd'
e = 'e'
f = 'f'
def __init__(self):
self.a = 'a'
self.b = 'b'
self.c = 'c'
b = B()
print(dict(b))
其他回答
Python3.x
return dict((key, value) for key, value in f.__dict__.items() if not callable(value) and not key.startswith('__'))
注意,Python 2.7中的最佳实践是使用新风格的类(Python 3中不需要),即。
class Foo(object):
...
另外,“对象”和“类”之间也有区别。要从任意对象构建字典,使用__dict__就足够了。通常,你会在类级声明你的方法,在实例级声明你的属性,所以__dict__应该是好的。例如:
>>> class A(object):
... def __init__(self):
... self.b = 1
... self.c = 2
... def do_nothing(self):
... pass
...
>>> a = A()
>>> a.__dict__
{'c': 2, 'b': 1}
一个更好的方法(由robert在评论中建议)是内置的vars函数:
>>> vars(a)
{'c': 2, 'b': 1}
或者,根据您想做的事情,从dict继承可能会更好。那么你的类已经是一个字典,如果你愿意,你可以重写getattr和/或setattr来调用和设置字典。例如:
class Foo(dict):
def __init__(self):
pass
def __getattr__(self, attr):
return self[attr]
# etc...
使用vars(x)而不是x.__dict__实际上更python化。
我认为最简单的方法是为类创建一个getitem属性。如果需要写入对象,可以创建自定义setattr。下面是一个getitem的例子:
class A(object):
def __init__(self):
self.b = 1
self.c = 2
def __getitem__(self, item):
return self.__dict__[item]
# Usage:
a = A()
a.__getitem__('b') # Outputs 1
a.__dict__ # Outputs {'c': 2, 'b': 1}
vars(a) # Outputs {'c': 2, 'b': 1}
Dict将对象属性生成到字典中,可以使用字典对象获取所需的项。
要从任意对象构建字典,使用__dict__就足够了。
这将遗漏对象从其类继承的属性。例如,
class c(object):
x = 3
a = c()
Hasattr (a, 'x')为真,但'x'没有出现在a.__dict__中