1

I am new to Python, and am learning about basic methods that can be used in Python in class. I have this homework problem that I do not really know how to solve, so I was wondering if you could help me with this. Here is the problem:

class Doughnut:
    categories = ['cakey', 'doughy']
    def __init__(self, category, flavor):
        if category not in Doughnut.categories:
            self.category = 'doughy'
        else:
            self.category = category
        self.flavor = flavor

    def ___________:
        return self.category + " " + self.flavor + "doughnuts" 

d = Doughnut('cakey', 'bacon')
print("I want 2 " + str(d) + "s please!") # I want 2 cakey bacon doughnuts please!

I need to know what to write in the blank statement between the second "def" and ":". Thank you in advance!

Nathan Bell
  • 167
  • 1
  • 14

3 Answers3

1

Both answers included in this question would work.

You could use either def __repr__(self): or def __str__(self):

luis.galdo
  • 543
  • 5
  • 20
1

You need the __str__() method. A full working implementation is below.

class Doughnut:
  categories = ['cakey', 'doughy']


  def __init__(self, category, flavor):
    if category not in Doughnut.categories:
        self.category = 'doughy'
    else:
        self.category = category
    self.flavor = flavor


  def __str__(self):
    return self.category + " " + self.flavor + " doughnuts"


d = Doughnut('cakey', 'bacon')
print("I want 2 " + str(d) + "s please!")
Matthew Gaiser
  • 4,558
  • 1
  • 18
  • 35
0

What you're looking for are magic methods: when python is asked to do something non-trivial, it will search for one of them in your class to see how to do it.

In your specific case, there are two methods that convert a class to a string, and str() will try to use them under the hood:

  • __str__ is expected to return a human-readable representation
  • __repr__ should return a unambiguous representation

For more details, refer to this post.

So I would suggest:

def __str__:
    return self.category + " " + self.flavor + "doughnuts"