【问题标题】:Way to iterate though object in python [closed]在python中迭代对象的方法[关闭]
【发布时间】:2015-12-29 11:58:00
【问题描述】:

在 python 中有没有办法像这样从对象中获取数据:

box = BoxWithOranges()
print box['color']
print box['weight']
print box['count']

而且更合规:

for index in range(box['count']):
    box[index].eat()

【问题讨论】:

  • 这个对象是一种字典还是什么?
  • 您在寻找这样的东西吗? stackoverflow.com/questions/2675028/…
  • @marmeladze 我认为它来自某个模块,因为 dict 没有 .eat() 方法...
  • 它看起来好像是一个容器,有自己的属性,还包含一个项目列表(橙子)。
  • 不清楚你在问什么,但我怀疑你的答案在data model

标签: python object properties


【解决方案1】:

您必须为您的班级实现__getitem____setitem__ 方法。这就是您使用 [] 运算符时将调用的内容。例如,您可以让班级在内部保留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

【讨论】:

  • 我认为关键是它需要一个索引或一个字典键。我想知道这是否意味着在__getitem____setitem__ 中区分整数和字符串。
猜你喜欢
  • 2019-08-20
  • 2019-07-27
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 2014-01-01
  • 1970-01-01
  • 2019-01-12
  • 2017-03-31
相关资源
最近更新 更多