1

This is a best practices question

Let say, I have a class object, like so:

class ClassOfObjects:
     def __init__(self, name):
       self.name = name
     ...

Lets say, I instantiate 3 of these objects

a = ClassOfObjects('one')
b = ClassOfObjects('two')
c = ClassOfObjects('three')

Now, I want to create a list of my objects. One obvious way is to create list object

ListOfObjects = [a,b,c]

I find that limiting. Specially when I trying to search find an object with a particular object. Is anyone aware of any best practices.

  • use a dictionary to store them if the problem is retrieving them – joaquin Apr 7 '12 at 6:40
7

You can have each instance register itself with the class when it's created:

class K(object):
     registry = {}
     def __init__(self, name):
         self.name = name
         self.registry[name] = self

Then K.registry is a dictionary of all the instances you've created, with the name as the key. You don't even need to assign the instance to a variable, since it's accessible through the registry. You can also iterate over the instances easily.

Perhaps if you share more information about your use cases, someone can provide a better alternative.

| improve this answer | |
  • also consider using a set; this can be more accurate depending on your requirements and semantics of equality/duplicates – Preet Kukreti Apr 7 '12 at 6:43
  • 1
    @kindall Does it matter if at line 5, I do K.registry[name] = self? Because I thought you supposed to do it like that? I have a question that is "bugged" because I didn't refer to the class, I referred to the self. – George Apr 7 '12 at 7:47
  • 1
    Since you're not assigning to the attribute registry of the instance, only modifying it, self or K (or better yet, type(self)) are equivalent ways to get to the same dict. – kindall Apr 7 '12 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.