2017-05-14 48 views
2
class Class(): 
    id_list = [] 

    def __init__(self, name, id): 
     self.name = name 
     self.id = id 
     Class.id_list.append(self.id) 

class1 = Class("Bob", 0) 
class2 = Class("John", 1) 

我想要做的是通過類的每個實例的ID,如果它匹配一個特定的ID然後它告訴我類的名稱,這是可能的嗎? 例如:如果我正在尋找「約翰」,我尋找身份證號碼1如何通過類變量找到某個類的特定實例?

+0

爲什麼不只是存儲的元組' (id,class_name)'? – River

+3

如果名稱是關鍵,要通過引用它的東西,那麼你應該使用的字典() –

+0

我使用類的不僅僅是這一點,我想知道是否有可能只使用類的更多。 –

回答

4

如果你只存儲在id_list類變量每個實例的id價值,有沒有簡單的方法來獲得在相應的名字。但是,如果您可以更改邏輯以在整個實例中存儲對整個實例的引用而不是id,那麼您將能夠查找您想要的任何屬性。如果id做查找是常見的,你可能想使用字典而不是列表以獲得更快的查找速度(雖然如果id值總是在0和每次1增加開始,你能夠索引也列入O(1)時間)。

嘗試這樣:

class Class: 
    instances = [] 

    def __init__(self, name): # no id arg needed 
     self.name = name # your code probably shouldn't have quotation marks around "name" 
     self.id = len(self.instances) # automatically use the next available id value 
     self.instances.append(self) # append a reference to the whole instance to the list 

    @classmethod 
    def lookup_class_name_by_id(cls, id): 
     if 0 <= id < len(cls.instances): 
      return cls.instances[id].name 
     raise ValueError("Invalid ID {}".format(id)) 
+0

這是一個完美的答案,很好的例子! :) –

2

如果我正確地理解了你,你想通過id函數創建一個搜索,這樣id就會鏈接到一個實例,你可以爲此創建一個字典,將該鍵作爲id和值作爲實例。

class Class(): 
    id_list = {} # id_list will be a dict instead 

    def __init__(self, name, id): 
     self.name = name # no quotation marks... 
     self.id = id 
     Class.id_list[self.id] = self # save the id as key and self as he value 

    @classmethod 
    def search_by_id(cls, id): 
     try: 
      return cls.id_list[id] # return the instance with the id 
     except KeyError: # error check for if id does not exist 
      raise KeyError("No user with id %s" % str(id)) 

class1 = Class("Bob", 0) 
class2 = Class("John", 1) 
print(Class.search_by_id(0).name) # prints Bob 
print(Class.search_by_id(1).name) # prints John 
print(Class.search_by_id(2).name) # prints raised a KeyError since id 2 doesn't exist yet: KeyError: 'No user with id 2' 
+0

Thas一個完美的答案! ;) –

0

如果你想,每次你實例,他們有一個新的ID的人,你可以這樣做:

class MyClass(): 
    ids = 0 
    id_list = {} 

    def __init__(self, name): 
     self.name = "name" 
     MyClass.ids += 1 
     self.myId = MyClass.ids 
     MyClass.id_list[self.myId] = self 

    def search_by_id(id): 
     return MyClass.id_list[id] 

bob = MyClass("bob") 
kyle = MyClass("kyle") 
print(bob.myId) 
print(kyle.myId) 
print(MyClass.search_by_id(2).name) 

>1 
>2 
>kyle 
相關問題