rlms
rlms

Reputation: 11060

Is storing instances of a class in a class variable a good pattern

One design pattern I use a lot in Python is this:

class Foo:
    foos = []
    def __init__(self, argument):
        initialize_instance()
        foos.append(self)

Does this have a name, and is it considered a useful pattern?

Upvotes: 3

Views: 101

Answers (1)

Gnucki
Gnucki

Reputation: 5133

I really don't think that this is a good practice in OOP (I'm not an expert in Python). The use of a static (like the list foos) is almost always a bad conception. Like said in the comments, a better solution is to set a service class (look at the SOA pattern in OOP) to index all your instances of Foo and retrieve them further.

However, do not think this is a variant of the registry pattern. This is rather an antipattern of this pattern preventing correct low coupling between classes. Of course, Python is not the better language to do a strong OOP and respect this, but I would'nt recommend to do that anyway.

Upvotes: 1

Related Questions