ptr
ptr

Reputation: 3384

Python: appending to a base class list/tuple member

I was asked this question a moment ago and couldn't think of a pythonic solution so I thought I'd throw it out here for a better viewpoint.

What is the best way to extend a base class variable tuple/list etc in a super class?

The following works...

class BaseClass(object):
    some_class_member = (1, 2, 3, 4, 5,)


class AnotherClass(BaseClass):
    some_class_member = BaseClass.some_class_member + (6, 7,)

a = BaseClass()
a.some_class_member  # (1, 2, 3, 4, 5)

b = AnotherClass()
b.some_class_member  # (1, 2, 3, 4, 5, 6, 7)

But doesn't seem very pythonic as you have to reference the BaseClass by name so would have to update it if the name changed. Is there a better way to go about this?

Upvotes: 5

Views: 1632

Answers (2)

emesday
emesday

Reputation: 6186

BaseClass in BaseClass.some_class_member does not mean super of AnotherClass. It just

BaseClass.some_class_member. You can access without instantiation.

 >>> BaseClass.some_class_member
 (1, 2, 3, 4, 5)

If your purpose is to access the value without instantiation, the simple answer is no. However, to access the value after instantiation.

How about?

class AnotherClass(BaseClass):
    def __init__(self):
        self.some_class_member += (6, 7,)

Upvotes: 2

OozeMeister
OozeMeister

Reputation: 4859

I can kind of see your point, however, you're already referencing the BaseClass by name due to specifying it as a parent of your new subclass.

In the interest of the "what if the name changes" scenario, you could provide another layer of inheritance:

class MyBaseClass(BaseClass):
    """ This is here so that all of my classes just inherits from this one """


class AnotherClass(MyBaseClass):
    super_special_member = MyBaseClass.super_special_member + (6, 7, )


class ClassThatDoesntNeedSuperSpecialMember(MyBaseClass):
    """ Cool. """

MyBaseClass would act as a sort of "constant" variable in that you can change what it inherits from and everything else will automatically update.

Upvotes: 3

Related Questions