可以通过python中的索引访问类实例吗?

时间:2017-11-23 20:08:31

标签: python oop indexing

例如,考虑我们有一个类'Agent',如下所示:

class Agent:

    def __init__(self, number):
        self.position = [] 
        self.number = number         
        for i in range(number):
             self.position.append([0, 0])

我可以通过以下方式创建一个类的实例:

agent = Agent(10)

然后通过以下方式访问第i个代理人的职位:

agent.position[i]

然而,这似乎不够优雅,对我而言,这有点违反直觉。相反,我想索引类实例本身。例如:

pos_i = agent[i].position

应该返回与上面的单行代码相同的答案。有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:0)

如果要重载索引操作符,只需重载类中的__getitem__方法。

class Agent:
    def __getitem__(self, key):
        return self.position[key]

>>> myobj = MyClass()
>>> myobj[3]

答案 1 :(得分:0)

如果你想这样做,你只需要一个包含所有实例的类级容器。

由于你的位置是以任意顺序创建的,我建议使用字典。

您可以填写班级“位置”词典。然后,您可以实现__getitem__方法来从此字典中检索元素:

class Agent:
   position = {}
   def __new__(cls, pos):
       if pos in cls.position:
           return cls.position[pos]
       instance = super().__new__(cls)
       cls.position[pos] = instance
       return instance

   def __getitem__(self, item):
        return self.position[pos]

但是,这只允许您从实例中检索给定位置的实例 - 即:

agent_5 = Agent(5)
agent_10 = agent_5[10] 

会起作用,但不起作用:

agent_10 = Agent[10] 

如果需要,您必须使用自定义元类,并将__getitem__方法放在那里:

class MAgent(type):
   def __getitem__(cls, item):
        return cls.position[pos]


class Agent(metaclass=MAgent):
   position = {}
   def __new__(cls, pos):
       if pos in cls.position:
           return cls.position[pos]
       instance = super().__new__(cls)
       cls.position[pos] = instance
       return instance
相关问题