Search code examples
pythonpython-2.7inheritanceabstract-classclass-method

Issues of choosing classmethod over inheritance in Python


What are the main issues I can come across if I choose to use classmethod over Inheritance in Python? A (silly) example would be:

class Pizza(object):
    def __init__(self, ingredients):
        self.ingredients = ingredients
        self.cooked = False

    def cook(self):        
        print "cooking"
        self.cooked = True

    # A pepperoni pizza using a factory method
    @classmethod
    def Pepperoni(cls):
        return cls("pepperoni")

# An onion pizza inheriting from Pizza base class
class Onion(Pizza):
    def __init__(self):
        ingredient = "onion"
        super(Onion, self).__init__(ingredient)

I know that

  • I cannot (easily) add custom methods to Pepperoni
  • I cannot make Pizza an abstract base class

anything else?


Solution

  • You seem to think of Pepperoni as a class in its own right, just like Onion. Whereas Onion is a class, Pepperoni is just a function living on Pizza. Sure one should not think of Pepperoni as a normal method, but really it is. The classmethod decorator effectively turns the Pepperoni method into a factory function, producing a new instance. The code is completely equivalent to just writing the function outside of the class:

    def Pepperoni():
        return Pizza("pepperoni")
    

    You wouldn't talk about "adding custom methods to Pepperoni" now, but really nothing has changed.