1

The requirements for the codes are as below: Create a class called Burrito. This burrito should have:

  • An attribute (is_california) is a boolean that indicates if the burrito is a California burrito (in other words, if it has fries in it!).

  • An instance-specific attribute, (contents) is a list of contents in the burrito.

  • A method, (add_fries). If there were not already fries in the contents list, this method should add fries to the list of contents and update is_california to be true.

and my codes are below:

class Burrito():
    def is_california(self):
        contents = []
        if 'fries' in contents:
            is_california = True
        if 'fries' not in contents:
            is_california = False
    
    def __init__(self,contents = []):
        self.contents = contents
        
    def add_fries(self):
        if 'fries' not in contents:
            contents.append('fries')

It does not work when I try to test the add_fries(), is there any improvements to be made? Thanks!

Michael M.
  • 10,486
  • 9
  • 18
  • 34
HELLOWORLD
  • 11
  • 1
  • `is_california = True` creates a local variable called `is_california` in your `is_california` function and sets it to `True` - you want to `return True` instead (and you probably want to look at `self.contents` and not some empty list you also created locally) – Grismar Oct 20 '22 at 02:43
  • Thanks! should I put in any values when defining contents? – HELLOWORLD Oct 20 '22 at 02:48

2 Answers2

0

A shorter one

class Burrito:

    def __init__(self):
        self.contents = []

    @property
    def is_california(self):
        return 'fries' in self.contents

    def add_fries(self):
        'fries' not in self.contents and self.contents.append('fries')

b = Burrito()
print(b.is_california) # False
b.add_fries()
print(b.is_california) # True
0

You don't need a method to check if the burrito is Californian, you can simply check when you update it (in __init__() and add_fries(). Like this:

class Burrito():
    def __init__(self, contents=[]):
        self.contents = contents
        self.is_california = 'fries' in contents

    def add_fries(self):
        if 'fries' not in self.contents:
            self.contents.append('fries')
            self.is_california = True


# Burrito 1
b = Burrito(['lettuce', 'cheese'])
print(b.is_california)  # => False
b.add_fries()
print(b.is_california)  # => False

# Burrito 2
b2 = Burrito(['fries', 'tomato'])
print(b2.is_california)  # => True

Some other answers seem to be doing this wrong. is_california must be a boolean attribute according to your question, not a method.

Michael M.
  • 10,486
  • 9
  • 18
  • 34