Warm tip: This article is reproduced from stackoverflow.com, please click
python

Is it better to include an object in every class or only when it's needed?

发布于 2020-03-27 10:21:12

Suppose I have the class 'Pizza':

Option 1:

class Pizza:
    def __init__(self, tools):
        self.tools = tools
        self.slices = []

    def cut(self, slices: int):
        self.slices = self.tools.pizza_cutter(slices=slices)

    def eat(self, slices: int):
        if len(self.slices) => slices:
            diff = len(self.slices) - slices
            self.slices[:diff]
        else:
            print('Not enough slices to eat!')

Option 2:

class Pizza:
    def __init__(self):
        self.slices = []

    def cut(self, slices: int, tools):
        self.slices = tools.pizza_cutter(slices=slices)

    def eat(self, slices: int):
        if len(self.slices) => slices:
            diff = len(self.slices) - slices
            self.slices[:diff]
        else:
            print('Not enough slices to eat!')

As you can see it either loads tools in __init__, or it just receives the tools instance in the method that actually uses it.

I am wondering, what is the best approach? Consider that there are multiple instances of Pizza created each loop and that at the end of this loop I cut() all the Pizzas

Questioner
A. Dandelion
Viewed
13
codeWonderland 2019-07-03 22:18

Generally I will determine whether or not to include something in a class by how I would describe it.

  • The first instance of your class Pizza contains all of the parts of the pizza and the tools to cut it.
  • The second class Pizza contains all the parts of a pizza.

When the word "and" comes into play I know that I've put too much into one class and need to separate it out. In this case, the tools are not an inherent part of a pizza. You can have a pizza without the tools to cut it. Pizza might be hard to cut without tools, but that doesn't make it any less of a pizza.

With this in mind, I would recommend keeping tools out of your pizza