Pre-class Assignment: Introduction to Object Oriented Programming (OOP)#
Day 6#
CMSE 202#
(image from realpython.com
)
✅ Put your name here
#Goals for Today’s Pre-Class Assignment#
By the end of this assignment, you should be able to:
Understand the concept of objects
Use predefined objects from imported libraries
Modify an existing class to define custom object
Assignment instructions#
Watch both videos (the first in Part 1 and the second in Part 3), read all included and linked content, and complete any assigned programming problems. Please get started early, and come to office hours if you have any questions and make use of Slack!
This assignment is due by 11:59 p.m. the day before class, and should be uploaded into the appropriate “Pre-class assignments” submission folder. Submission instructions can be found at the end of the notebook.
1. What are objects?#
Functions and decision (if/else) statements are very powerful tools for writing programs in Python. Combining them with libraries like numpy
, scipy
makes Python very powerful and easy to use.
We’ve previously learned how functions can perform various tasks by grouping together commonly performed tasks to be called from different parts of the script (or notebook). But every function needs data to work on: a function for multiplication requires at least 2 numbers to multiply, the len
function requires a string, a list, or an array to return its length, etc.
If we combine the data and functions into one data structure, we get objects. The object, like in a real world, combine both the data
(i.e. the attributes of the object) and the methods (or functions) that can perform manipulations with the object’s attributes.
To make things even more interesting, everything in Python is an object: integer, string, list, and dictionary. Every object has data associated with (for the integer, this is the value, an integer number) and there is a list of functions we can perform on a given object. Examples of objects that you already encountered before are numpy
arrays, lists, dictionaries, and Pandas DataFrames.
✅ Do this: To learn more about the idea behind using objects and what is commonly referred to as “Object Oriented Programming” (OOP), watch the video below and answer the questions below the video.
# Don't forget to watch the video in full-screen mode!
from IPython.display import YouTubeVideo
YouTubeVideo("3dA4XE6l7YI",width=800,height=450) # objects
Quick questions#
After watching the video above, answer the following two questions to review the most important facts about objects.
✅ Question 1: Each object is made up of three (3) key components. What are these three components?
✎ Do This - Erase the contents of this cell and replace it with your answer to the above question! (double-click on this text to edit this cell, and hit shift+enter to save the text)
✅ Question 2: In your own words, explain why would we combine the attributes (data) and methods (functions) into objects? In what ways might that make the programming easier?
✎ Do This - Erase the contents of this cell and replace it with your answer to the above question! (double-click on this text to edit this cell, and hit shift+enter to save the text)
2. Using objects#
Objects are building blocks of Python - everything in Python is an object. Even basic variable types, such as integers, floats, strings, lists and dictionaries, are objects.
How do we use objects, if they are already in Python? How do we “call” their methods? The method name needs to be specified after the object name and separated by a full stop (”.
”) from the object name. Everything else is the same as calling a function.
2.1 Using built-in objects#
Objects are everywhere in Python and there is no way to avoid objects in Python. Even basic string manipulation can be done in Object-Oriented Programming (OOP) way. You have been using objects in Python without even knowing that. It’s so easy!
Below are examples of calling methods from built-in objects and you have been using many of them on daily basis in this class already. The numpy
example also shows the similarity between using functions to get the shape of 2D array and then perform the same task using the built-in method (the OOP way).
✅ Review the following examples and make sure you understand everything that is happening.
# example of converting the string into upper case
# defined a variable - string
name = "Hello world!"
# converting the string into upper case string
lcase_name = name.upper()
# printing original and converted strings
print("Name:", name)
print("Uppercase name:", lcase_name)
# replacing characters in string
# again, defining a string
name = "Hello world!"
# replace work "world" with "class"
new_name = name.replace("world", "class")
# printing original and changed string
print("Name:", name)
print("New name:", new_name)
import numpy as np
# define an 2D array
board = np.arange(20).reshape((4,5))
print(board)
# get dimensions of the board
# using len function
print("len():\n Number of rows:", len(board), "number of columns:", len(board[0]))
# using numpy shape method
print("numpy.shape():\n Number of rows:", np.shape(board)[0], "number of columns:", np.shape(board)[1])
# using object attributes
print("board.shape:\n Number of rows:", board.shape[0], "number of columns:", board.shape[1])
To call methods defined in an object, you write the variable name (remember, everything in Python is an object), followed by dot (.
) and the method name. You can also notice that the statement
np.shape(board)
is doing exactly the same: calling there method shape
from object np
(which is numpy) and then return the shape of given 2D array.
As mentioned before, every object has methods associated with it and Jupyter notebook can help you find which methods are available for a given object. To get available methods for given object, do the following:
write the variable (object name) name
write a dot (
.
) after the variablepress TAB to get the list of possible methods for a given object; the methods will be listed in a pop-up window next the cursor.
To print ALL the available attributes and methods of a given object, you can use dir
function. You may notice that names of some attributes and methods begin with an underscore (_
) - these attributes and methods are intended for internal use inside the object rather than being user-facing attributes and methods (they are mostly called from other methods in the object).
When you find the method that you think could be the right one, you are interested which parameters you need to defined to selected method. Jupyter notebook can help here too. To get parameters and usage of given method in the object, use question mark after the method name - the same way as for functions.
✅ For example, to get parameters for shape
method from numpy
, write the following into cell and execute the cell (press SHIFT+ENTER
):
np.shape?
# test out np.shape? here!
✅ Question 3: Write a bit code that first defines a new list and then prints possible methods you can call for that list. Write three of the methods into the answer field below. (Hint: the function that can output the list of all possible methods was referenced in the text above).
# put your code here
✎ Do This - Erase the contents of this cell and replace it with your answer to the above question! (double-click on this text to edit this cell, and hit shift+enter to save the text)
✅ Question 4: Write a bit code that creates a new dictionary and prints all possible methods you can call for that dictionary. Write three of the methods into the answer field below.
# put your code here
✎ Do This - Erase the contents of this cell and replace it with your answer to the above question! (double-click on this text to edit this cell, and hit shift+enter to save the text)
2.2 String and list manipulation#
Let’s practice working with objects by doing a bit of string and list manipulation. In the cell below, you’re provided a long string to work with.
# define a long string
text = "In this assignment, you are learning about Object Oriented Programming (OOP), which is a bit different from functional programming style that we have been using up to this point. While much of the content in this assignment will likely be new to you and a might be little confusing at first, you'll have more time to explore these concepts during the in-class assignment as well."
Do your best to write the code in the cell below each of the following question to achieve the task. The tasks can be achieved with a just few lines of code, so if you find that your code is 20 lines or more, you may have take a less efficient approach and you may want to consider other ways to tackle the problem. You may also want to google a helpful phrase or two like: “splitting a Python string” (as an example)
✅ Question 5: Write a bit of code that prints a Python list that contains the words in the string “text
” defined in the previous code cell. Hint: there is a space (
) between the words and you can “split” a string into list of words.
# put your code here
✅ Question 6: Write a bit of code that will replace all instances of the word assignment to task in the text
string. Hint: try using the replace using method from string
class.
# put your code here
✅ Question 7: Write a bit of code that will count the number of times word assignment
appears in the string text
. This can be achieved in two ways: using loops and lists, and using methods from string
class. Hint: use TAB
key or the dir()
function to get a list of possible methods and ?
to see the description and arguments for each method. For example: to get the parameters for the numpy .sum()
function, you would write: np.sum?
# put your code here
✅ Question 8: Write a bit of code that converts first 5 words to upper case and prints them out. Do this in two different ways:
first with lists and loops (Hint: split string to words and convert first 5 into upper case)
try to do it using methods from
string
class (Hint: convert the whole string into upper case and split it into words and print the first 5 words)
Try to accomplish the task both ways, but do not spend too long figuring out how to do it using either approach (we mean it, don’t spend more than 5-10 minutes on this, if you don’t immediately see a way to do it – its more important to move onto Part 3 of this assignment). If you didn’t figure it out, note this in the survey and we’ll cover this in class.
Hint: use TAB
key to get possible methods and ?
to see the description and arguments for each method.
# put your code here
3. Creating your own objects#
Now that we know how to use built-in objects, it’s time to create our own objects. Defining the object in Python is similar to defining a function, with few extra things we have to be careful about. The main difference is in fact, that the object is storing both attributes and methods.
✅ Do this: Watch the video below to learn how custom objects are defined in Python and how they are used. Answer the questions below the video.
# Don't forget to watch the video in full-screen mode!
from IPython.display import YouTubeVideo
YouTubeVideo("1j9BFXsZvp0",width=800,height=450) # objects
Quick questions#
After watching the video above, answer the following two question to overview the most important facts about objects.
✅ Question 9: What is the keyword used to define a class in Python?
✎ Do This - Erase the contents of this cell and replace it with your answer to the above question! (double-click on this text to edit this cell, and hit shift+enter to save the text)
✅ Question 10: What is the purpose of attributes in objects?
✎ Do This - Erase the contents of this cell and replace it with your answer to the above question! (double-click on this text to edit this cell, and hit shift+enter to save the text)
3.1 Few important things before creating an object#
Now that we know how to use the objects and we learned a little bit how to create them (did you watch the video above?), it’s time to create our own objects. Defining the object in Python is similar to defining a function. First one needs to define a class to be able to use is later - the same as with functions.
The most important thing you have to do to define a class:
the class is defined by using a keyword
class
, followed by name of the class
There are some important information to keep in mind when creating classes:
the first argument to every method inside class is
self
(this is defined by Python naming convention and allows the object to reference “itself”)attributes inside the class are addressed by adding
self.
before the variable name:self.name = 'Milka'
to set the value to variablename
; note the dot (.
) after theself
calling methods inside class follows the same idea as attributes: if you want to call the method from inside the class, the method name needs to have
self.
before the method name:self.get_name()
methods and attributes behave the same way as they would outside of the class (types, conversion between types, assignment, etc.)
3.2 Defining object a new object: Animal
#
We will create a class to store information about animals in a Zoo, or maybe later, to create list of characters from the Madagascar movie. It is common when creating a class to start with a basic class description, that includes only a few attributes and methods, test the basic class and then add both attributes and methods into the class as needed. The class (as objects) can evolve and/or grow in time.
In the cell below is the base definition of the Animal
class with the following attributes (see the code below and try to identify the variables that correspond to this attributes):
animal kind (e.g. zebra, lion, elephant, penguin)
animal nickname
when the animal arrived to the Zoo (date string in format yyyy-mm-dd)
To initialize the Animal
object, and set and retrieve the attributes in object, the following methods are defined in the class (see the code below and try to identify each method):
initialize the
Animal
class (__init__
), which accepts “kind
”, “nickname
” and broughtto_zoo
as parameters.set the animal
name
(set_name
), which allows you to change the name of the animal by providing a newname
.get the current animal nickname (
get_name
), which doesn’t not require any input.
✅ Do this: Look at the code below and try to identify the attributes and methods. You can add comments to the code the same way you’ve done with previous code.
Note: the __init__
method is a special one associated with all Python objects. This function is called by automatically when the object is first created and is used to initialize a set of starting attributes. It is referred to as a “constructor” in object oriented programming terminology.
3.3 Adding missing methods#
✅ Do this: Review how methods are created and special pay special attention to the details how class attributes are defined and used (note the use of self
). Armed with the knowledge you’ve gleaned from the provided code, add the following methods to the class (you can use existing methods to as a starting point for your new methods):
Create a method to set the animal ‘kind’, use
set_kind
as the method name.Create a method to set the date for when the animal was brought to the Zoo, use
set_arrive_to_zoo
as the method name.Create a method to get the animal nickname, use
get_kind
as the method name.Create a method to get the date of when the animal was brought to the Zoo, use
get_arrive_to_zoo
as the method name.
# Here is a skeleton of Animal class with few methods defined, but with some missing.
class Animal:
def __init__(self, kind, name, to_zoo=''):
''' Initialize the Animal object.
Inputs are
kind : the type of animal (string)
name : the nickname for the animal (string)
to_zoo : the date the animal came to the zoo (in 'yyyy-mm-dd' format)
'''
# this is:
self.kind = kind
# this is:
self.name = name
# this is:
self.brought_to_zoo = to_zoo
def set_name(self, name):
''' Set animal's name. '''
self.name = name
def get_name(self):
''' Return animal's name. '''
return self.name
✅ Do this: Now run the code in the cell below to test your class. The code creates few objects with animal names from the Madagascar movie and prints out what kind of animal are they together with their nickname along with the arrival date for one of the animals. The output of your testing code should be:
Original information:
Alex is a zebra.
Kowalski is a tiger.
---
Corrected information:
Alex is a lion.
Kowalski is a penguin.
---
When did Marty arrive?
Marty was brought to the zoo on 2005-05-27
If there is an error, go back to class definition and correct the code. With correctly implemented methods, the test code should run without any errors.
# create object for defining few characters from The Madagascar
alex = Animal('zebra', 'Alex')
marty = Animal('zebra', 'Marty')
skipper = Animal('penguin', 'Skipper')
kowalski = Animal('tiger', 'Kowalski')
print("Original information:")
# printing animal names and kinds
print("{0} is a {1}.".format(alex.get_name(),alex.get_kind()))
print("{0} is a {1}.".format(kowalski.get_name(),kowalski.get_kind()))
print('---')
print("Corrected information:")
# oops, there was an error in the information for Alex and Kowalski, set the correct info:
alex.set_kind('lion')
print("{0} is a {1}.".format(alex.get_name(),alex.get_kind()))
kowalski.set_kind('penguin')
print("{0} is a {1}.".format(kowalski.get_name(),kowalski.get_kind()))
print('---')
print("When did Marty arrive?")
# Set the date that marty wasd brought to the zoo and then print it
marty.set_arrive_to_zoo("2005-05-27")
print("{0} was brought to the zoo on {1}".format(marty.get_name(),marty.get_arrive_to_zoo()))
4. Additional reading (not mandatory)#
For more information about classes in Python, check out this link:
Important: The web page above includes comprehensive information about classes and you are NOT expected to read everything presented! Few topics beyond 9.3.2 Class Objects will be covered in the next class.
Follow-up Questions#
Copy and paste the following questions into the appropriate box in the assignment survey include below and answer them there. (Note: You’ll have to fill out the assignment number and go to the “NEXT” section of the survey to paste in these questions.)
Which function in Python would you use to print attributes and methods defined for an object?
Each object is made up of three (3) key components. Which are these three components?
What is the keyword used to define a class in Python?
What is the purpose of attributes in objects?
Assignment wrap-up#
Please fill out the form that appears when you run the code below. You must completely fill this out in order to receive credit for the assignment!
from IPython.display import HTML
HTML(
"""
<iframe
src="https://cmse.msu.edu/cmse202-pc-survey"
width="800"
height="800px"
frameborder="0"
marginheight="0"
marginwidth="0">
Loading...
</iframe>
"""
)
Congratulations, you’re done!#
Submit this assignment by uploading it to the course Desire2Learn web page. Go to the “Pre-class assignments” folder, find the appropriate dropbox link, and upload it there.
See you in class!
© Copyright 2024, Department of Computational Mathematcs, Science and Engineering at Michigan State University