在 python 中遍历对象的方法
Way to iterate though object in python
在 python 中有没有办法像这样从对象中获取数据:
box = BoxWithOranges()
print box['color']
print box['weight']
print box['count']
更合规:
for index in range(box['count']):
box[index].eat()
您必须为 class 实施 __getitem__
和 __setitem__
方法。这就是您使用 []
运算符时将调用的内容。例如,您可以让 class 在内部保留 dict
class BoxWithOranges:
def __init__(self):
self.attributes = {}
def __getitem__(self, key):
return self.attributes[key]
def __setitem__(self, key, value):
self.attributes[key] = value
演示
>>> box = BoxWithOranges()
>>> box['color'] = 'red'
>>> box['weight'] = 10.0
>>> print(box['color'])
red
>>> print(box['weight'])
10.0
在 python 中有没有办法像这样从对象中获取数据:
box = BoxWithOranges()
print box['color']
print box['weight']
print box['count']
更合规:
for index in range(box['count']):
box[index].eat()
您必须为 class 实施 __getitem__
和 __setitem__
方法。这就是您使用 []
运算符时将调用的内容。例如,您可以让 class 在内部保留 dict
class BoxWithOranges:
def __init__(self):
self.attributes = {}
def __getitem__(self, key):
return self.attributes[key]
def __setitem__(self, key, value):
self.attributes[key] = value
演示
>>> box = BoxWithOranges()
>>> box['color'] = 'red'
>>> box['weight'] = 10.0
>>> print(box['color'])
red
>>> print(box['weight'])
10.0