Mahi
Mahi

Reputation: 21932

Have each subclass contain a list of its own?

I wish to have a base class, that would make each subclass to contain a list without needing to do it manually for each subclass? For example, when I create a Subclass from my BaseClass, I want my Subclass to have element_list list automatically. Currently I do it like so:

class BaseClass:
    element_list = ['Base Element', 'More Element\'s']
    def do_stuff(): pass

class Subclass(BaseClass):
    # Replaces BaseClass' element_list
    element_list = ['Sub Element', 'More Sub Element\'s']
    def do_sub_stuff(): pass

Now as it stands, this seems easy to do manually, but I'd like this class system to be as user-friendly as possible for people who don't know that much of it (basically only read a tutorial hot to make these subclasses), and most classes are gonna have an empty element_list, or have the elements added later in the code after defining the class.

I'd love to have it so that there's an empty list by default, even if one is not manually defined in the subclass, and that each subclass would automatically have its own unique list.

Is this possible?

Upvotes: 1

Views: 67

Answers (1)

Daniel
Daniel

Reputation: 42778

It's almost never a good idea to have mutable object as class attributes. Just use tuples, you can always overwrite the attribute if you need to modify your list.

Upvotes: 3

Related Questions