0

If I want to make a base class that other classes will inherit from, but will never use the class variables from, what should I set the class variables to?

For example:

class Spam:
    time_to_cook = None

    def eat(self):
        ...

class SpamWithEggs(Spam):
    time_to_cook = Minutes(5)

    def eat(self):
        ...

All subclasses will have their own time_to_cook, so its value in Spam has no effect on the functioning of the program.

class Spam:
    time_to_cook = None

looks good to me, but it doesn't give any information about the type of time_to_cook. Therefore I'm leaning towards

class Spam:
    time_to_cook = Minutes(0)

but that could give the misleading impression that the value of time_to_cook is actually used.

I'm also considering missing it out entirely, and mentioning it in the docstring instead.

rlms
  • 10,650
  • 8
  • 44
  • 61
  • 2
    You could also set it to None or zero or whatever placeholder value you want, *and* mention in the docstring what kind of value it should be set to. – BrenBarn Jun 14 '14 at 18:17
  • Note that `SpamWithEggs` is _not_ a subclass of `Spam` (because the latter isn't listed as a base class of the former). – martineau Jun 14 '14 at 19:50
  • @martineau OOPs, fixed now. – rlms Jun 14 '14 at 20:51
  • 1
    Can you set it to `Minute(0)`, then put a doc string saying it is not used in the base class? – Hai Vu Jun 14 '14 at 23:42

2 Answers2

1

I like shavenwarthog's answer, but it is a little strange to use an exception directly as the value of an attribute. So, instead, you could pass it something that will raise an error no matter what method you call:

class Complainer:
    def __getattr__(self, name):
        raise NotImplementedError 

and use it like so:

class Spam(object):
    time_to_cook = Complainer()

then, whenever you try to call any of Minute's methods, you'll get an exception. Alternatively, if you're never going to be instantiating Spam directly, you can just make it entirely abstract and not worry about it.

Patrick Collins
  • 10,306
  • 5
  • 30
  • 69
0

I suggest NotImplementedError. It doesn't give any hint as to what the type should be, but it's very clear that the value should not be used directly.

class Spam(object):
    time_to_cook = NotImplementedError

    def eat(self):
        ...

class SpamWithEggs(Spam):
    time_to_cook = Minutes(5)
johntellsall
  • 14,394
  • 4
  • 46
  • 40
  • 2
    Except that `NotImplementedError` is a type, so using it as value this way is a little weird IMHO, even though (obviously) legal. – martineau Jun 14 '14 at 22:25
  • @martineau: true. `NotImplementedError()` is a little more proper, as it's an instance vs a type, but in neither case does it signify the type of the variable. It's a hack :) – johntellsall Jun 15 '14 at 21:37