rlms
rlms

Reputation: 11060

Base class class variable values in Python

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.

Upvotes: 0

Views: 139

Answers (2)

Patrick Collins
Patrick Collins

Reputation: 10594

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.

Upvotes: 1

johntellsall
johntellsall

Reputation: 15170

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)

Upvotes: 0

Related Questions