2017-09-15 2 views
0

내가이 주어진 목록개체가 목록에서 자신의 위치를 ​​말할 수 있습니까?

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

에서 객체의 무리가 개체의 인덱스를 반환 클래스 anObject를 내 함수를 작성하는 방법이있을 것입니다. 의사 코드 :

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

EDIT : 또한 목록에서 개체를 제거하는 클래스 내에서 함수를 사용할 수 있는지 궁금합니다. 이것은 내가 위의 것을 필요로하는 것입니다.

+1

의사 코드는'List'를'objectList'로 변경하고'def' 줄에'self'를 필수로 넣었을 때 실제로 그렇게 할 것입니다. 아니면 당신이 목록의 이름을 모른다면 어떻게 할 것인가? 그리고이 객체를 포함하고있는 목록이 있다면 그것도 확실하지 않은가? 나는 객체가 그것을 참조하는 다른 모든 객체를 결정할 수 있다고 생각하지 않는다. – Kevin

+0

특별한 경우, 그렇습니다. 오브젝트가리스트에서 중복 참조를 가질 수 있으면, 아니오. –

+1

음 .... obj = object(); items = [obj, obj, obj, obj, obj]'- 어떤 위치는 정확하게 그것이라고 생각하기로되어있는 객체입니까? –

답변

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) 
관련 문제