Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
OOD Example (CS 189)
class Robot:
# An example class representing a robot
def __init__(self, robot_type, color):
"""
This is run when an instance of the class is created
:param robot_type: String representing the type of robot (humanoid, roomba, kilobot)
:param color: Color (string) of the robot
"""
self.color = color
self.robot_type = robot_type
if robot_type == 'roomba':
self.num_legs = 0
self.height = 0.07
elif robot_type == 'humanoid':
self.num_legs = 2
self.height = 1.8
elif robot_type == 'kilobot':
self.num_legs = 3
self.height = 0.03
def fits_under(self, obj_height):
"""
Will the robot fit under the object?
:param obj_height: clearance height of the object (m)
:return: Boolean, will it fit
"""
return self.height < obj_height
def say_color(self):
"""
Print the color of the robot in a string
:return: None
"""
print "Beep boop, I'm", self.color
def grow(self):
"""
Increase the robot height by 1 cm
:return: None
"""
self.height += 0.01
# Using the class
# Create a new robot:
my_roomba = Robot('roomba', 'blue')
# Access different fields in the Robot object:
print my_roomba.color
print my_roomba.height
# Call object methods:
my_roomba.fits_under(0.05) # -> False
my_roomba.fits_under(1.0) # -> True
# Some methods don't return anything
my_roomba.say_color() # Prints "Beep boop, I'm blue"
# Methods can modify (mutate) the object (with or without returning something)
my_roomba.height # -> 0.07
my_roomba.grow() # Changes height but doesn't return anything
my_roomba.height # -> 0.08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.