nitin
nitin

Reputation: 7358

Python Classes and Collections

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.

Upvotes: 1

Views: 335

Answers (1)

kindall
kindall

Reputation: 184091

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.

Upvotes: 8

Related Questions