We have seen how to write a REALLY basic class:
class Student(object):
# Simple Student class
Attributes go here
A constructor is a method that we use to create an instance of a class; these instances are called objects. Here is an example of one:
self.first_name_str
# Initializes the object
def __init___(self, first='', last='',id=0):
self.first_name_str = first
self.last_name_str = last
self.id_int = id
Self refers to the object itself. First, last and id are initial values
that we give the constructor so it can initialize
first_name_str
,
last_name_str
and
id_int
the three attributes of the class.
We also need a method called __str__
that
can return our object as a character string, so we can print the object's
data. It would look like this:
# String representation, eg, for printing
def __str__(self):
return "{} {}, ID:{}".format\
(self.first_name_str, self.last_name_str, id_int)
We can create an object of this class by writing
my_student = Student("John", "Smith")
I can print out its contents by writing
print(my_student)
It will print out
John Smith, ID:0
because I didn't specify an ID number
Create the Student
class and initialize with
a name and an ID number. Then create a class called
Course
, which has three properties: Department
Abbreviation (e.g, "CSC
"), a course number
(e.g,, "171
"), and the number of credits. Then
create an instance of a course, give it some initial data and print it out.