Day 20: Pre-class Assignment: introduction to Object Oriented programming (OOP)#

✅ Put your name here

#

(image from realpython.com)

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 existing class used 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 7:59 p.m. the day before class, and should be uploaded into the “Pre-class assignments” submission folder. Submission instructions can be found at the end of the notebook.


Part 1. What are objects?#

Functions and decision statements are very powerful tools for writing the program in Python. Combining them with libraries like numpy, scipy makes Python very powerful and easy to use.

Previously we 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 that can perform manipulation with the object’s attributes.

To make things even more interesting, everything in Python is an object: integer number, string, list, and dictionary. Every variable has its data (for integer, this is the value, an integer number) and there is a list of functions we can perform on a given number. Examples of objects that you already encountered before are numpy arrays, lists, dictionaries, Pandas datasets.

Now, to learn more about the idea behind using objects, 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=640,height=360)  # objects 

Quick questions#

After watching the video above, answer the following two questions to review the most important facts about objects.

Question: Each object is made up of three (3) key components. What are these three components?

Put your answer here!

Question: In your own words, explain why would we combine the attributes (data) and methods (functions) into objects? Would that make the programming easier?

Put your answer here!


Part 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 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 method (OOP way).

# 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 a 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 variable

  • press 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 function dir. 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 (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: Write a code that defines a list and prints possible methods you can call for that list. Write three of the methods into the answer field below.

# put your code here

Put your answer here!

Question: Write a code that creates a dictionary and prints possible methods you can call for that dictionary. Write three of the methods into the answer field below.

# put your code here

Put your answer here!

2.2 String and list manipulation#

Let’s practice using objects and do string and list manipulation. You will use a sentence from the beginning of this pre-class assignment for practicing.

# define a long string
text = (f"Because the concept of Object Oriented Programming (OOP) is very different from functional programming
that we were using till now, the last part of this pre-class assignment will be repeated in the next pre-class assignment.
It was added to this assignment so you could look it over the material in advance as there is only one day between classes.")

Do this: Write the code in the cell below each question to achieve the task. The tasks can be achieved with a few lines of code, not more (without the comments, of course). If your code is 20 lines or more, maybe you are using the wrong method.

Question: Write a code that prints a list of words in the string text. Hint: there is a space ( ) between words and you can split the string into list of words.

# put your code here

Question: Write a code that will replace all words assignment to task in the string text. Hint: try using the replace using method from string class.

# put your code here

Question: Write a 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 to get possible methods and ? to see the description and arguments for each method. For example: to get the parameters for numpy sum, you write: np.sum?

# put your code here

Question: Write a 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 the way using string class methods. If it was too difficult to use string methods to count, 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
# 4. convertinf first 5 words to uppercase
# 4a: using loops and lists
wordsUpper = []
for word in text.split(" ")[:5]:
    wordsUpper.append(word.upper())

print("Words:", wordsUpper)

# 4b: OOP way
wordsUpper = text.upper().split(" ")[:5]
print("Words:", wordsUpper)

Part 3. Creating own objects#

Now that we know how to use build-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 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=640,height=360)  # objects

Quick questions#

After watching the video above, answer the following two question to overview the most important facts about objects.

Question: What is the keyword used to define a class in Python?

Put your answer here!

Question: What is the purpose of attributes in objects?

Put your answer here!

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.

  1. 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

  1. There are some important information to keep in mind when creating classes:

  • the first argument to every method inside class is self (the name defined by naming convention)

  • attributes inside the class are addressed by adding self. before the variable name: self.name = 'Milka' to set the value to variable name; note the dot (.) after the self

  • calling methods inside class follows the same idea as attributes: method name need 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 Animal#

We will create a class to store information about animals in the ZOO, or maybe later, to create list of characters in a 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 Animal class with following attributes (see the code below and try to identify the variables that correspond to this attributes):

  • animal kind (zebra, lion, elephant, penguin)

  • animal nickname

  • when the animal arrived to the ZOO (date string in format yyyy-mm-dd)

To initialize the 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, accepting “kind”, “nickname” and ‘brought to the zoo’ as parameters

  • set animal ‘name’

  • to get the animal nickname

Look at the code below and try to identify attributes and methods. You can add comments to the code the same way as before.

3.3 Adding missing methods#

Look how methods are created, pay attention to the details how class attributes are defined and used (the use of self), and add the following methods to the class (you can use existing methods to help out):

  • set the animal ‘kind’, good method name would be set_kind

  • set the date when the animal was brought to the ZOO, good method name would be set_arrive_to_zoo

  • to get the animal nickname, good method name would be get_kind

  • to get the date then the animal was brought to the ZOO, good method name would be get_arrive_to_zoo

Do this: Use the cell below your code to test your class. 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.

# 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 object Building. '''
        # this is: 
        self.kind = kind
        # this is:
        self.name = name
        # this is:
        self.brought_to_zoo = to_zoo
        return self

    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 use the code in the cell below to test your class. The code creates few objects with animal names from Madagascar movie and prints out what kind of animal are they together with their nickname. The output of your testing code should be:

Alex is a zebra.
Kowalski is a tiger.
Alex is a lion.
Kowalski is a penguin.
# create object for defining few characters from The Madagascar
alex = Animal('lion', 'Alex')
marty = Animal('zebra', 'Marty')
skipper = Animal('penguin', 'Skipper')
kowalski = Animal('tiger', 'Kowalski')

# printing animal's names
print("{0} is a {1}.".format(alex.get_name(),alex.get_kind()))
print("{0} is a {1}.".format(kowalski.get_name(),kowalski.get_kind()))

# ups, correct info for Alex and Kowalski
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()))
Alex is a lion.
Kowalski is a tiger.
Alex is a lion.
Kowalski is a penguin.

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.)

  1. Which function in Python would you use to print attributes and methods defined for an object?

  2. Each object is made up of three (3) key components. Which are these three components?

  3. What is the keyword used to define a class in Python?

  4. What is the purpose of attributes in objects?


Part 4. Additional reading (not mandatory)#

For more information about classes in Python, check out these 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.


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/cmse801-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 2023, Department of Computational Mathematics, Science and Engineering at Michigan State University