如何通过索引来处理类实例

时间:2017-07-17 17:33:18

标签: python python-3.x class

我如何通过索引解决类实例?例如,如果我有

class Body(object):
    def __init__(self, attribute1, attribute2)
        self.attribute1 = attribute1
        self.attribute2 = attribute2

class1 = Body(1,2)
class2 = Body(3,4)

我希望能够做到这样的事情:

Body[1].attribute1

并返回值1.

4 个答案:

答案 0 :(得分:1)

您始终可以将实例放在列表中:

classes = [Body(1,2), Body(3,4)]

然后你可以索引列表:

>>> classes[0].attribute1   # attribute1 of the first element in the list
1

>>> classes[1].attribute2   # attribute2 of the second element in the list
4

请注意,索引以0而不是1开头。

顺便说一下,:之后你错过了def __init__(self, attribute1, attribute2)

如果你真的想要你的行为,你可以使用元类来做(不推荐!):

class IndexableClass(type):
    def __init__(self, *args):
        """Called when the class (not instances!) is created."""
        self._instances = []   # a class attribute keeping references to the instances

    def __getitem__(self, index):
        """Called when the class is indexed."""
        return self._instances[index]

    def __call__(self, *args, **kwargs):
        """Called when a new instance is created."""
        res = type.__call__(self, *args, **kwargs)
        self._instances.append(res)
        return res

class Body(object, metaclass=IndexableClass):
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

class1 = Body(1,2)
class2 = Body(3,4)

Body[0].attribute1   # 1

答案 1 :(得分:0)

您必须将它们放入某种类型的集合中,例如列表或元组。

class Body(object):
    def __init__(self, attribute1, attribute2)
        self.attribute1 = attribute1
        self.attribute2 = attribute2


class1 = Body(1,2)
class2 = Body(3,4)
bodies = [class1, class2]
bodies[1].attribute1

答案 2 :(得分:0)

您可以列出类实例:

classes = [class1, class2]
print(classes[1].attribute1)

答案 3 :(得分:0)

class Body(object):
    bodies = []
    def __init__(self, attribute1, attribute2)
        self.attribute1 = attribute1
        self.attribute2 = attribute2
        Body.bodies.append(self)

class1 = Body(1,2)
class2 = Body(3,4)
Body.bodies[0]
Body.bodies[1]

Bodies是静态列表。每次创建新的身体对象时,它都会自动将其自身添加到列表中。