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)
我想要做的是查看每个Class实例的ID,如果它与某个ID匹配,那么它会告诉我类的名称,这可能吗? 例如:如果我正在寻找“John”,我会寻找ID号1
答案 0 :(得分:4)
如果您只在id
类变量中存储每个实例的id_list
值,那么就没有简单的方法来获取相应的名称。但是,如果您可以更改逻辑以在列表中存储对整个实例的引用而不是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))
答案 1 :(得分: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'
答案 2 :(得分: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