-1

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?

Rodrigo E. Principe
  • 1,281
  • 16
  • 26

1 Answers1

1

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.

jmd_dk
  • 12,125
  • 9
  • 63
  • 94
  • Yes, I understand the difference between them, but I'm having a hard time trying to decide whether I should use inheritance or just make classmethods.. Imagine you have to code *Pizza* for a store which has a set of 30 different kinds, what would you do? – Rodrigo E. Principe Oct 23 '17 at 14:57
  • I would simply utilize the `ingredients` argument of `Pizza`: `pizza_with_onion = Pizza('onion')`. The factory function should be used if you somehow need to instantiate a pizza from something other than its ingredients. A whole new class would be needed if you decided also to make kebabs, which is different from a pizza but might still share quite a few methods. – jmd_dk Oct 23 '17 at 15:01
  • Thanks mate! I guess making a factory class although I don't need to *instantiate a pizza from something other than its ingredients* doesn't make any harm =) – Rodrigo E. Principe Oct 23 '17 at 15:20