Object-oriented programming
#!/usr/bin/env python
class Student:
'contains students, email, name ...'
def __init__(self, name ="John Doe", courses =[]):
self.name = name
self.courses = courses
print "Created a class instance for "+ name
def printDetails(self):
print "Name: ", self.name
print "Courses: ", self.courses
def enroll(self, course):
self.courses.append(course)
student1 = Student("Mary", ["L548"])
print "Input the courses which", student1.name, "is enrolled in."
newcourse = raw_input ("Type the course number or 'stop' ")
while newcourse != "stop":
student1.enroll(newcourse)
print "Input the courses which", student1.name, "is enrolled in."
newcourse = raw_input ("Type the course number or 'stop' ")
student1.printDetails()
Exercises
1.1 Add further attributes to the student class (phone number, email
address, degree, etc).
1.2 Create a list of students. Let users add new students to the list.
Ask the user for the name of a student and then print his/her details.
1.3 Create a method creditHours that computes the number of credit hours
for a student assuming that every class is a three credit class.
1.4 Create a class Employee that contains information
about names, ages and positions. What could be useful methods
for the class?
2) Modules
Code can be stored in different files (modules) and can be imported.
A module must have an extension "py". It should contain exactly one
class which has the same name as the module. To import a module from
the current directory the system path may need to be changed:
import sys
sys.path.append(".")
The Student module (in the file Student.py) can then be imported
with from Student import *.
(import Student would also work but then
all methods would have to be prefixed with "Student.".)
Exercises
2.1 Using the previous example,
separate the main code and the class definition. Save the class
definition as a module Student.py and import it into the file that
contains the main code.