对象可以在列表中表明自己的位置吗?

时间:2017-09-15 16:04:39

标签: python python-3.x

我在列表中有一堆对象

objectList = []
for i in range(0, 10):
    objectList.append(AnObject())

鉴于此,是否有办法在类AnObject中编写一个返回对象索引的函数。在伪代码中:

class AnObject:
    def returnIndex():
        if self in List:
           return List.index(self)

编辑:此外,我想知道你是否可以在一个类中有一个函数从列表中删除该对象。这主要是我需要的上述内容。

1 个答案:

答案 0 :(得分:0)

import uuid

class AnObject:
    def __init__(self):
        self.object_id = uuid.uuid4()
        # print("created object with id: " + str(self.object_id)
    def find_me_in_list(self, a_list):
        """
        This method will find the lowest index occurrence of this 
        object in the specified list "a_list".
        :param: a list reference 
        :return: String indicating whether object was found 
        """
        try:
            pos = a_list.index(self)
            print("Found object at position: " + str(pos))
            return True
        except ValueError:
            print("Did not find this object")
            return False

    def remove_me_from_list(self, a_list):
        """
        This method will remove this object from the specified list 
 "a_list".
        The method removes all occurrences of the object from the 
 list by using a while loop
        :param: a list reference 
        :return: None
        """
        if self.find_me_in_list(a_list):
            while self in a_list:
                print("Removing this object from position " + str(a_list.index(self)) + " in list")  ### for debugging
                a_list.remove(self)
        else:
            print("object does not exist in this list")

some_obj = AnObject()
some_other_obj = AnObject()  ### we will not add this object instance to the list

objectList = []
for i in range(0, 10):
    objectList.append(AnObject())
    # print(objectList[i].object_id) ### for debugging

### let's add some_obj to objectList five times
for i in range(0, 5):
    objectList.append(some_obj)

### let's try to find these objects
some_obj.find_me_in_list(objectList)
some_other_obj.find_me_in_list(objectList)

print("***" * 20)

### let's try to delete these objects
print("let's try to delete these objects")

some_other_obj.remove_me_from_list(objectList)

some_obj.remove_me_from_list(objectList)