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

2024-05-19 00:05:28 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我们有一个“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

它应该返回与上面的单行代码相同的答案。有办法做到这一点吗?你知道吗


Tags: 实例inselfnumberforinitdef方式
2条回答

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

既然你的职位,举个例子,是按任意顺序创建的,我建议你用字典。你知道吗

你只需要填写班级级别的“职位”字典。然后就可以实现__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

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

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

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

相关问题 更多 >

    热门问题