Reputation: 131
I'm working on a project and it would make it easier for me to code if we can identify class attributes based on their unique instances. example
class MyClass:
def __init__(self, unique_id):
self.unique_id = unique_id
and later
class1 = MyClass(1)
class2 = MyClass(2)
Is it possible to do get the object class1 as an output if
output = instance whose unique_id == 1
Upvotes: 0
Views: 99
Reputation: 814
Option A :
If you are planing on adding the id's in a consecutive way you could enter them all into a list :
class_list = []
class_list.append(MyClass(1))
class_list.append(MyClass(2))
And then get them using
class_list[index]
Option B :
If you arent going to them consecutively you could do the following
class_dict = {}
class_dict{"some_id"} = MyClass("some_id")
class_dict{"some_id2"} = MyClass("some_id2")
and then access as following :
class_dict["some_id"]
Option C - Prefered:
Personally I would recommend the following :
class MyClass:
static_dict = {}
def __init__(self, unique_id):
self.unique_id = unique_id
MyClass.static_dict[unique_id] = self
def get_class_by_id(unique_id):
return static_dict[unique_id]
and then you could access as following:
MyClass.get_class_by_id("some_id")
Upvotes: 1
Reputation: 24232
You can keep a dict of instances:
class MyClass:
_instances = {}
def __init__(self, unique_id):
self.unique_id = unique_id
self._instances[unique_id] = self
@classmethod
def instance_by_id(cls, id):
return cls._instances[id]
a = MyClass(1)
b = MyClass(2)
c = MyClass.instance_by_id(1)
print(c)
print(a)
#<__main__.MyClass object at 0x7fa9dd0bfbe0>
#<__main__.MyClass object at 0x7fa9dd0bfbe0>
Upvotes: 1