Changes

Jump to: navigation, search

OPS435 Python Lab 6

50 bytes added, 14:59, 27 November 2017
PART 2 - Understanding Class Structure
</source>
:# This is how you give the class a name, now when you need to create a new Student object we know the class is called Student. '''Everything''' indented underneath the '''class Student:''' will be apart a part of the class.
:# Next indented under the class is the __init__() method. This works similarly to a function, it contains code indented underneath it, that code is executed when you call the function. But __init__() is a special method, instead of manually calling this method, it will automatically be executed when we create a object. Inside the __init__() we create variables(object attributes), these are created using '''self.name''', where '''name''' is the name of the attribute. The '''self.''' portion before the variable name is to let the class know that this variable can be accessed from anywhere inside the class and outside of the class, as a public attribute. Lets come back to this later.<source lang="python">
def __init__(self, name, number):
print('GPA of student ' + self.name + ' is ' + str(gpa / len(self.courses)))
</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. So before ? Before you can use a class, we must create a new object. A single class description can be used to create as many objectsas you like, not just a single object. This Our '''Student''' class will be used to create lots of different student objects, each object will be created using the blue print blueprint of the class, but they will all be separate and contain separate data to store each and every students 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 difference data inside, even if some of the data is the same.
:# Import the python script into your ipython environment:<source lang="python">
from student import Student

Navigation menu