Today wraps up classes and objects with our continuing example of a Midshipman class, but now used properly in a separate file that we need to import. We will also look at the WordCloud library introduced in the Twitter lab, and discuss its classes and functions therein.
from mids import Midshipman
# Create objects!
mids = list()
mids.append( Midshipman('Santa Cruz Cernik', 100) )
mids.append( Midshipman('Christie', 100) )
mids.append( Midshipman('Dollahite', 85) )
mids.append( Midshipman('Jordan', 100) )
# Do stuff!
mids[2].complain('homework')
mids[1].order_chipotle()
mids[1].chop()
mids[3].order_chipotle()
mids[0].parade()
# Print info!
for mid in mids:
if mid.health < 90:
print('WARNING!', end=' ')
mid.pretty_print()
mid.order_chipotle()
The code above only works if we have a separate file called mids.py that defines the class like so:
# mids.py
class Midshipman:
def __init__(self, name, h):
self.name = name
self.health = h
self.QPR = 4.0
def pretty_print(self):
print(self.name, '\t', end='')
if len(self.name) < 8:
print('\t\thealth = ', end='')
elif len(self.name) < 16:
print('\thealth = ', end='')
else:
print('health = ', end='')
print(self.health)
def complain(self, topic):
print(topic, 'is the worst!')
self.health -= 5
def order_chipotle(self):
print(self.name, 'ordering chipotle!')
# update some health variable
self.health += 10
def chop(self):
print('Beat Army, sirs!')
print('I love SD211!')
self.health -= 2
def parade(self):
print('March march march')
self.health -= 20