06.0 Python‎ > ‎Python Notes‎ > ‎Python OOPs‎ > ‎

Balloons: Python OOPs

Build a balloon

You should be able to construct balloons of any capacity. You will also need to be able to inflate and deflate air from a balloon. If you try to add too much air, the balloon will pop. You can not remove more air than there is in the balloon.

 

For the balloon class,

HAS-A: attributes

capacity : the amount of air the balloon can hold before it will pop

volume: the amount of air currently in the balloon

isPopped: true or false whether the balloon is popped. All balloons created are not popped.

 

RESPONDS-TO: methods

constructors: special initialization code used when creating a new Balloon(), the parameter will include the capacity of the balloon.  

The name of the constructor is __init__


def inflate(self, amount)

The parameter amount is the amount of air to be added to the balloon.

 

def deflate(self, amount)

The parameter amount is the amount of air to be removed from the balloon.

 

def display(self)

The display method displays a current state of an object. 

 

This is a template that could be used to create a object in Python that will model a balloon.

__author__ = 'Mister V'

class Balloon:
# __init__ is the constructor of the Balloon class
# it is called every time a new balloon is created.
def __init__(self, capacity):
self.capacity = capacity
self.volume = 0
self.isPopped =False

def display(self):
print ("capacity: ", self.capacity)
print ("volume: ", self.volume)
print ("isPopped: ", self.isPopped)
print ("_"*20)

def inflate(self, amount):
self.volume = self.volume + amount

def deflate(self, amount):
self.volume = self.volume - amount
# this code creates the object from the above class
# then uses the inflate and deflate methods to change the state of the object
# display is used to see the state of the object
b1 = Balloon(10)
b1.display()
b1.inflate(7)
b1.display()
b1.deflate(3)
b1.display()
print("done")

Copy this template to your Python IDE.
Run this as a program.

Part 1
Improve the model to make it more representative of a Balloon:
  1. Have the balloon pop if too much air is added
  2. make sure a balloon that isPopped can not be inflated
  3. make sure that the balloon can not contain a negative volume or capacity
  4. By adding the line b2 = Balloon(5)you can create a second balloon that will inflate and deflate independently of b1
  5. Try it!
Part 2
Add other checks to ensure that the balloon is well behaved.
Create more balloon of various capacities and states of inflation
Comments