我有一个Python类,存储一些字段,并有一些属性,如
class A(object):
def __init__(self, x, y):
self.x = x
self.y = y
@property
def z(self):
return self.x+1
Run Code Online (Sandbox Code Playgroud)
我需要对课程进行哪些更改才能完成
>>> a = A(1,5)
>>> dict(a)
{'y':5, 'z':2}
Run Code Online (Sandbox Code Playgroud)
在这里我指定我想回到y和z?我不能只是使用,a.__dict__因为它会包含x但不包含z.我希望能够指定任何可以访问的内容__getattribute__.
kin*_*all 12
__iter__()向类中添加一个方法,该方法将对象项的迭代器作为键值对返回.然后,您可以将对象实例直接传递给dict()构造函数,因为它接受一系列键值对.
def __iter__(self):
for key in "y", "z":
yield key, getattr(self, key)
Run Code Online (Sandbox Code Playgroud)
如果您希望它更灵活一些,并允许在子类(或以编程方式)上轻松覆盖属性列表,则可以将键列表存储为类的属性:
_dictkeys = "y", "z"
def __iter__(self):
for key in self._dictkeys:
yield key, getattr(self, key)
Run Code Online (Sandbox Code Playgroud)
如果您希望字典包含所有属性(包括从父类继承的属性),请尝试:
def __iter__(self):
for key in dir(self):
if not key.startswith("_"):
value = getattr(self, key)
if not callable(value):
yield key, value
Run Code Online (Sandbox Code Playgroud)
这排除了以"_"开头的成员以及可调用的对象(例如类和函数).
我认为解决这个问题的合理方法是创建一个asdict方法.如果你想要指定你想要dict包含哪些键,我假设你对调用该方法时传递的信息感到满意.如果那不是你的意思,请告诉我.(这包含了kindall的优秀建议.)
class A(object):
def __init__(self, x, y):
self.x = x
self.y = y
@property
def z(self):
return self.x+1
def asdict(self, *keys):
if not keys:
keys = ['y', 'z']
return dict((key, getattr(self, key)) for key in keys)
Run Code Online (Sandbox Code Playgroud)
测试:
>>> A(1, 2).asdict('x', 'y')
{'y': 2, 'x': 1}
>>> A(1, 2).asdict()
{'y': 2, 'z': 2}
Run Code Online (Sandbox Code Playgroud)