Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: appending to a base class list/tuple member

Tags:

python

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?

like image 390
ptr Avatar asked Jun 18 '14 14:06

ptr


2 Answers

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.

like image 187
OozeMeister Avatar answered Nov 17 '22 15:11

OozeMeister


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,)
like image 2
emeth Avatar answered Nov 17 '22 13:11

emeth