9314197
9314197

Reputation: 241

How to define subclasses that differ only in one function's argument without repeating myself?

I'm creating classes in python like this:

class x(abstract_class, another_class):
    @property
    def do_something(self):
        return something('a', 'x')

class y(abstract_class, another_class):
    @property
    def do_something(self):
        return something('a', 'y')

This happens for many more classes. It seems long and unnecessarily repetitive, since do_something is not the only thing that happens within each class. Since 'x' and 'y' are so similar, is there any way I can create them both at once, or do anything else to stop the repetition?

Upvotes: 0

Views: 68

Answers (2)

martineau
martineau

Reputation: 123453

Since you're already using multiple inheritance, you could "do something" like this if you don't want (or can't) modify the two existing classes you're already using as base classes. It's based on the suggestion @Charles Duffy posted in a comment, and relies on the special attribute that classes have named , not suprisingly, __name__.

Note I've also modified your code to follow PEP 8 - Style Guide for Python Code's naming conventions.

class AbstractClass: pass
class AnotherClass: pass


def something(s1, s2):
    print('something({!r}, {!r}) called'.format(s1, s2))


class Mixin:  # Yet another class.
    @property
    def do_something(self):
        something('a', self.__class__.__name__)


class X(AbstractClass, AnotherClass, Mixin):
    pass


class Y(AbstractClass, AnotherClass, Mixin):
    pass


if __name__ == '__main__':

    x = X()
    y = Y()

    x.do_something  # -> something('a', 'X') called
    y.do_something  # -> something('a', 'Y') called

Upvotes: 1

John
John

Reputation: 2127

Put

def do_something(self):
    return something('a', self.__class__.__name__)

in another_class and they can both inherit it so that you don't have to replicate the code.

Upvotes: 2

Related Questions