Search code examples
pythonclass-variables

Python - appending to class-level lists in derived class definitions


class A (object):
    keywords = ('one', 'two', 'three')

class B (A):
    keywords = A.keywords + ('four', 'five', 'six')

Is there any way to change A.keywords to <thing B derives from>.keywords, sort of like super(), but pre-__init__/self? I don't like repeating class names in definitions.

Usage:

>>> A.keywords
('one', 'two', 'three')
>>> B.keywords
('one', 'two', 'three', 'four', 'five', 'six')

Solution

  • Actually, you can. Write a descriptor that checks the class's bases for an attribute with the same name and add the passed attributes to its value.

    class parentplus(object):
        def __init__(self, name, current):
            self.name = name
            self.value = current
    
        def __get__(self, instance, owner):
            # Find the attribute in self.name in instance's bases
            # Implementation left as an exercise for the reader
    
    class A(object):
        keywords = ('one', 'two', 'three')
    
    class B(A):
        keywords = parentplus('keywords', ('four', 'five', 'six'))