OOP
Object-oriented programming (OOP) is a programming paradigm/technique that organizes software design around objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior. It is useful in big projects (above ~500 lines), it makes the writing and understanding of the code easier. (For smaller codes – like in our case – we deliberately pretend it to be complex to understand what is happening.)
Exercise: There are several courses with "hours to attend" and "credit" values. Choose your courses and calculate the sum of their hours and sum of their credits.
# Format of one entry: (name, hours to attend, credit)
all_courses = [
("Info1", 3, 4),
("Info2", 3, 3),
("Combi1", 4, 4),
("Combi2", 3, 3)]
my_courses = ["Info1", "Combi1"]
def hourstotal(mycourses, allcourses):
hours = 0
for course in allcourses:
if course[0] in mycourses:
hours += course[1]
return hours
def credittotal(mycourses, allcourses):
credits = 0
for course in allcourses:
if course[0] in mycourses:
credits += course[2]
return credits
print((hourstotal(my_courses, all_courses)))
print((credittotal(my_courses, all_courses)))
Problem: Modify a course entry: store the presense requirements also.
# Format: (name, hours, presence required, credit)
all_courses = [
("Info1", 3, 2, 4),
("Info2", 3, 2, 3),
("Combi1", 4, 2, 4),
("Combi2", 3, 1, 3)]
my_courses = ["Info1", "Combi1"]
def credittotal(mycourses, allcourses):
credits = 0
for course in allcourses:
if course[0] in mycourses:
credits += course[3] # <<< modified here
return credits
print(hourstotal(my_courses, all_courses))
print(credittotal(my_courses, all_courses))
Even if you store the same values except one, you have to modify the credittotal
function, even if the credit entry did not change.
This is problematic if you have complicated data in the entries. And also you can forget to rewrite some of the functions when you insert new data.
This is why the tuple is not sustainable. One solution is to use a dictionary:
# Format: (name, classes in hours, presence required, credit)
all_courses = [
{"name": "Info1", "hour": 3, "presence": 2, "credit": 4},
{"name": "Info2", "hour": 3, "presence": 2, "credit": 3},
{"name": "Combi1", "hour": 4, "presence": 2, "credit": 4},
{"name": "Combi2", "hour": 3, "presence": 1, "credit": 3},]
my_courses = ["Info1", "Combi1"]
def hourstotal(mycourses, allcourses):
hours = 0
for course in allcourses:
if course["name"] in mycourses:
hours += course["hour"]
return hours
def credittotal(mycourses, allcourses):
credits = 0
for course in allcourses:
if course["name"] in mycourses:
# <<< you don't have to modify any more
credits += course["credit"]
return credits
print(hourstotal(my_courses, all_courses))
print(credittotal(my_courses, all_courses))
This is not so bad, but there are still some problems.
"name"
but don't have "presence"
You can solve this by adding a newcourse
function which creates a correct course entry.
In this case you have to use that function every time you create a new course entry.
# use this function when creating a new course
def newcourse(allcourses, name, hour, precense, credit):
x = {"name": name, "hour": hour,
"precense": precense, "credit": credit}
allcourses.append(x)
newcourse(all_courses, "Info3", 2, 2, 3)
my_courses = ["Info1", "Combi1"]
print(all_courses)
print(hourstotal(my_courses, all_courses))
print(credittotal(my_courses, all_courses))
This solves the problem of incorrect or incomplete entries if you use the newcourse
function.
Since you cannot call that function without the proper parameters.
This solution is the closest to the concept of a class
.
The class is similar to a type, like list
and an object is an instance of a class.
Like 5
is an instance of int
.
Let's make a class named Course
. It is a custom to use capitalized names as class names.
class Course:
pass
This works, but does nothing. One can create an instance by the name of the class and a parenthesis:
c = Course()
And you can add values to that instance:
c.name = "Info2"
c.hour = 3
print(c.name, c.hour)
You can access the members with the dot (.
) operator.
The instance is on the left-hand-side of the dot and the required member is on the right-hand-side.
The member can be a value and a function, like the append
of a list.
You can add data members after creating the instance, it is better to add them during the creation.
This is the constructor:
class Course:
def __init__(self, name, hour, precense, credit):
self.name = name
self.hour = hour
self.precense = precense
self.credit = credit
The constructor is a special method called __init__
.
That function is executed when an instance is created: write the name of the class and after that the parameters in a paranthesis.
c = Course( x, y, ... )
The self
parameter is the object to be created, you can set the members using the function parameters.
Let's see the course example with a class:
all_courses = [
Course("Info1", 3, 2, 4),
Course("Info2", 3, 2, 3),
Course("Combi1", 4, 2, 4),
Course("Combi2", 3, 1, 3)]
my_courses = ["Info1", "Combi1"]
c = Course("Info3",2,2,2)
c.name
def hourstotal(mycourses, allcourses):
hours = 0
for course in allcourses:
if course.name in mycourses:
hours += course.hour
return hours
def credittotal(mycourses, allcourses):
credits = 0
for course in allcourses:
if course.name in mycourses:
credits += course.credit
return credits
print(hourstotal(my_courses, all_courses))
print(credittotal(my_courses, all_courses))
Now let's make a class representing complex numbers, called Complex
.
class Complex:
def __init__(self, real, imaginary):
self.re = real
self.im = imaginary
z = Complex(4, 3)
print(z.re, z.im)
We write an add function:
class Complex:
def __init__(self, real, imaginary):
self.re = real
self.im = imaginary
def complex_add(z1, z2):
new_re = z1.re + z2.re
new_im = z1.im + z2.im
return Complex(new_re, new_im)
z1 = Complex(4, 3)
z2 = Complex(-2, 1)
z3 = complex_add(z1, z2)
print(z3.re, z3.im)
It is better to put the add function inside the class definition, since it is used to add Complex
numbers and nothing else.
class Complex:
def __init__(self, real, imaginary):
self.re = real
self.im = imaginary
def add(z1, z2):
new_re = z1.re + z2.re
new_im = z1.im + z2.im
return Complex(new_re, new_im)
z1 = Complex(4, 3)
z2 = Complex(-2, 1)
z3 = Complex.add(z1, z2)
print(z3.re, z3.im)
Even better without writing the name of the class in front of the function. The following is a method:
class Complex:
def __init__(self, real, imaginary):
self.re = real
self.im = imaginary
def add(self, z2):
new_re = self.re + z2.re
new_im = self.im + z2.im
return Complex(new_re, new_im)
z1 = Complex(4, 3)
z2 = Complex(-2, 1)
z3 = z1.add(z2) # <<< method
print(z3.re, z3.im)
The method's first parameter is self
, which is the object on the left-hand-side of the dot.
The method's name is on the right-hand-side of the dot. After that the other parameters.
In this case we say: add z2
to self
(which is now z1
).
It can be even nicer.
class Complex:
def __init__(self, real, imaginary):
self.re = real
self.im = imaginary
def __add__(self, z2):
new_re = self.re + z2.re
new_im = self.im + z2.im
return Complex(new_re, new_im)
z1 = Complex(4, 3)
z2 = Complex(-2, 1)
z3 = z1 + z2 # <<< the __add__ method is called
print(z3.re, z3.im)
The special name __add__
marks an operator, namely +
but you can call it by the exact name:
z4 = z1.__add__(z2)
print(z4.re, z4.im)
The special method __add__
is called when there is a +
operator after a Complex
instance.
The left-hand-side of the +
becomes self
and the right-hand- side is the parameter. The result will be the returned object.
A special method can be a number of things, like __sub__
, __mul__
, __div__
. But the __init__
was that, too.
These are special because they can be called other than their name. These special names are defined by python. They always start with a double underscore and end with a double underscore.
There is a small problem left:
print(z3)
This is not nice, but there is a special method used for printing:
class Complex:
def __init__(self, real, imaginary):
self.re = real
self.im = imaginary
def __add__(self, z2):
new_re = self.re + z2.re
new_im = self.im + z2.im
return Complex(new_re, new_im)
# used by print
def __str__(self):
return str(self.re) + " + " + str(self.im) + "i"
z1 = Complex(4, 3)
z2 = Complex(-2, 1)
z3 = z1 + z2
print(z1)
print(z2)
print(z3)
str(Complex(3, 2))
The __str__
method should return a string, that is what will be printed.
This method is called when the user wants to print the object or convert it to string.
However that is not perfect yet:
print(Complex(0, 0)) # 0
print(Complex(3, 0)) # 3
print(Complex(-2, 1)) # -2 + i
print(Complex(-2, -1)) # -2 - i