Changes

Jump to: navigation, search

OPS435 Python Lab 6

71 bytes removed, 09:27, 21 January 2020
no edit summary
<font color='red'>
'''** DO NOT USE - TO BE UPDATED FOR CENTOS 8.0 **'''
</font>
= LAB OBJECTIVES =
* Create new type of objects using the Class construct and investigate different ways in using them. :Python is an object oriented programming language. Python uses the concept of "objectsobject" to store data(attributes) and code(methods) efficiently for later use. By using objects, programming languages gain the advantage of making large/complex programs into smaller and modular objectscodes, which can be used or shared with other codeusers/programs. In Python, almost everything that we have used is actually an object with a specific purpose, however starting in this lab we will create our own objects, and investigate different ways to use them.
== PYTHON REFERENCE ==
:In previous labs, you have been advised to make notes and use online references. This also relates apply to learning about objected object oriented programming to help becoming "overwhelmed" with the volume of information in this lab.
:Below is a table with links to useful online Python reference sites (by category)document for Classes and objects. You may find these references useful when performing assignments should study the information given below and make sure you understand the key concepts introduced and labsdiscussed before start working on this lab.
{| class="wikitable" | style="margin-left:20px; border: 2px solid black;"
|- style="background-color:white;border:none;"
| style="border: 2px solid black;" valign="top"|
:Handling Errors &amp; ExceptionsUsing Classes
| style="border: 2px solid black;" valign="top"|
:[https://docs.python.org/3/tutorial/errorsclasses.html Errors &amp; ExceptionsClasses]
|- style="background-color:white;border:none;"
| style="border: 2px solid black;" valign="top"|
:Built-in ExceptionsClasses and Objects
| style="border: 2px solid black;" valign="top"|
:[httpshttp://docsgreenteapress.python.orgcom/3thinkpython2/libraryhtml/exceptionsthinkpython2016.html Built-in ExceptionsThink Python Chapter 15]
|- style="background-color:white;border:none;"
| style="border: 2px solid black;" valign="top"|
:ListsClasses and functions
| style="border: 2px solid black;" valign="top"|
:[httpshttp://docsgreenteapress.python.orgcom/3thinkpython2/tutorialhtml/introductionthinkpython2017.html#lists ListsThink Python Chapter 16]
|- style="background-color:white;border:none;"
| style="border: 2px solid black;" valign="top"|
:DictionariesClasses and methods
| style="border: 2px solid black;" valign="top"|
:[httpshttp://docsgreenteapress.python.orgcom/3thinkpython2/tutorialhtml/datastructuresthinkpython2018.html#dictionaries DictionariesThink Python Chapter 17]
|- style="background-color:white;border:none;"
| style="border: 2px solid black;" valign="top"|
:Using Classes
| style="border: 2px solid black;" valign="top"|
:[https://docs.python.org/3/tutorial/classes.html Classes]
|}
 
== Key Concepts related to Python Class and Object ==
* Programmer-defined types
* Class Object
* Class methods: __init__, __str__, etc
* Class instance: attributes and methods
* Object instantiation
* Object Attributes
* Pure Function
* Scopes and Namespaces: local, nonlocal, and global
* Class definition syntax
* Class and Instance variables
* Iterators and Generators
 
* Operator overloading
= INVESTIGATION 1: Creating Classes =
== PART 1 - Creating a Class ==
:The Each object of a class that is written we write in Python can contain variables, functions, code, but none of the code is executed or run until the class is used to create the an object. Remember that the class is a blueprint for how your object will work, the object that will be created is what will actually be running the code. This part of a class works in the same way as a function definition, the function doesn't run until it's executed, code inside classes dondoesn't run until the they are made into objects.
:'''Perform the Following Steps:'''
:#Launch your Centos VM, open a shell terminal (as a regular user) and start a new ipython3 session:<source lang="python">ipython3</source>:#Create a new python script in the lab6 directory:<source lang="pythonbash">%cd ~/ops435/lab6%vim ~/ops435/lab6/student.py
</source>
:#Place the following content inside the new python script and save it. Read through this script and the comments inside.<source lang="python">
print('Student Number: ' + self.number)
</source>
:# This next method accepts some arguments. The first argument of the method is '''self''', this is a required syntax for making methods inside of a class, and allows the method to access any variables you created/saved in the class previously, such as, '''self.courses'''. This method will take two additional arguments, : course, and grade. The method will then store these inside a dictionary '''self.courses''', with the key being '''course''' and the value being '''grade'''.<source lang="python">
# Add a new course and grade to students record
def addGrade(self, course, grade):
</source>
:# Now that the class has been broken down, the code inside is simple on it's own, but what does it mean when it all works together? Before you can use a class, we must create a new object. A single class description can be used to create as many objects as you like, not just a single object. Our '''Student''' class will be used to create lots of different student objects, each object will be created using the blueprint of the class, but they will all be separate and contain separate data to store each and every student's data. Try to think of an object as any other python data structure (list, set, dictionary): you can create multiple dictionaries and store different data inside, even if some of the data is the same.
:# Import In a new file, import the python script into your ipython environmentStudent class:<source lang="python">
from student import Student
</source>
student1 = Student('John', '013454900')
</source>
:# Now that the object '''student1''' has been created, Have a look closely at the components inside contents of the object. This is a look into the objects '''namespace'''student1:<source lang="python">dirprint(student1.name)</source>:# Notice anything familiar in here? This will display all attributes(name, number, courses) that were created with '''self.variableName''', it also shows all the methodsprint(displayStudent, displayGPA, addCourse) that were created too. Take a closer look at some of these different attributes and methods.<source lang="python">student1.namestudent1.number)print(student1.courses)
student1.displayStudent()
</source>
</source>
:# Take a closer look at some of these different attributes and methods.<source lang="python">
print(student2.name)print(student2.number)print(student2.courses)
student2.displayStudent()
</source>
</source>
:# Investigate what has changed in each object:<source lang="python">
print(student1.name)print(student1.courses)print(student2.name)print(student2.courses)
</source>
:# The method '''addGrade()''' changes the '''self.courses''' dictionary. But both student1 and student2 have their OWN courses dictionary.
:# Once an object is created the attributes inside may be modified externally. Though you may need to be careful, if a value is a string, and you change it to another type such as a integer or a list, it's possible the class was not designed to deal with the different type and may throw a error when you run a method. For example, changing the name to a integer would break the displayStudent method, because it would try and concatenate strings and integers(maybe the method should be written better.<source lang="python">
# student1.name is a string like any other
print(student1.name)
student1.name = 'Jack'
student1.name
print(student1.name)
len(student1.name)
::*The script should contain no errors
:::'''Sample Run 1:'''<source lang="python">
python3 ./lab6a.py
Student Name: John
Student Number: 013454900
['cpp244', 'ipc144']
</source>
:::'''Sample Run 2 (with import into ipython3):'''<source lang="python">
from lab6a import Student
student1.displayStudent()
# Will print: 'Student Name: Jack\nStudent Number: 931686102'
student1.displayGPA()
# Will print: 'GPA of student Jack is 1.0'
student1.displayCourses()
# Will print: ['ops535']
student2 = Student('Jen', 987654321)
 
student2.addGrade('uli101', 0.0)
student2.displayGPA()
# Will print: 'GPA of student Jen is 0.0'
student2.displayCourses()
# Will print: []
</source>
::3. Exit the ipython3 shell, download Download the checking script and check your work. Enter the following commands from the bash shell.<source lang="bash">
cd ~/ops435/lab6/
pwd #confirm that you are in the right directory
python3 ./CheckLab6.py -f -v lab6a
</source>
::4. Before proceeding, make certain that you identify any and all errors in lab6a.py. When the checking script tells you everything is OK before proceeding - proceed to the next step.
<br><br>
# What happens if you try and make a copy of an object?
# When does the __init__() method get executed?
# What is an attribute? How to do you create an attribute?
# What is a method?
# What is the difference between a method and a function?
# What is self used for in an object?
# What does it mean to instantiate an object?
# Import the Student class into ipython3, instantiate some objects, and try changing different attributes, and adding new attributes.
# Make a copy of lab6a.py called lab6practice.py, make the Student class accept another argument called program. When you create the new object: student = Student('name', '123456789', 'CTY'). Can you print the new students program out with student.program?
# Create a new method in lab6practice.py that checks to make sure the program is either "CTY" or "CNS", if it's not one of these, change the value to "unknown". Make sure the attribute is changed after your object is created.
[[Category:OPS435-Python]]
1,760
edits

Navigation menu