Let’s take a second pass at object oriented programming in Python.
Object oriented programming is about creating new types to model data used in the program.
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def is_old(self):
return self.age > 40
person = Person('G. H. Hardy', 70)
print person.is_old()
In object oriented programming in inheritance defines an “is a” relationship between types.
To continue the example we could say a student is a person. This would create a Student class which is a sub-class of Person. Students have things that normal people don’t have like a GPA.
Extending the class allows us to extend or override the functionally given by the base. If we don’t override a name in the new class accessing that name will use functionality defined in the base. If we do override a name it we can still access the base class definition using super.
from person import Person
class Student(Person):
def __init__(self, name, age, gpa):
self.gpa = gpa
super(Student, self).__init__(name, age)
def is_honor_student(self):
return self.gpa > 3.0
student = Student('G. H. Hardy', 70, 4.0)
print student.is_old()
print student.is_honor_student()