Methods can modify an object's attributes:
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
c = Counter()
c.increment()
c.increment()
print(c.count) # 2
You can also use the special __str__ method to define how an object is printed:
class Dog:
def __init__(self, name):
self.name = name
def __str__(self):
return f'Dog: {self.name}'
print(Dog('Buddy')) # Dog: Buddy
📋 Instructions
Create a `Restaurant` class for Bob's Burgers:
- Attributes: `name`, `menu` (a list), `revenue` (starts at 0)
- Method `add_item(item)` — adds to menu
- Method `sell(item, price)` — adds to revenue if item is on menu
- Method `status()` — prints name, menu, and revenue
Create the restaurant, add items, make some sales, and show the status!
In sell(), check if item is in self.menu first. If yes, add price to self.revenue.
⚠️ Try solving it yourself first — you'll learn more!
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
c = Counter()
c.increment()
c.increment()
print(c.count) # 2