Object-Oriented Programming is simply the manipulation and interaction of different objects. It has many benefits, including eliminating the need to write duplicate code. A good example of this is the creation and interaction of classes, the blueprints for objects.
If I wanted to emulate the workings of a school, I can create a few classes to represent this. For example I can create separate student, and teacher classes.
class Teacher(object):
def __init__(self, name, subject):
self.name = name
self.subject = subject
class Student(object)
def __init__(self, name):
self.name = name
Bob = Teacher(Bob, English)
Joey = Student(Joey)
Now I have created (a representation of) a teacher named Bob who teaches English and a student Joey.
But hold on, since both a student and teacher are people, I can create a class named Person and have the Student and Teacher class inherit from that Person class. This way, if I ever wanted new Student and Teacher attributes, like something universal like age, sex or height, I would only need to edit the parent class, Person, instead of editing several different classes.
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
class Teacher(Person):
def __init__(self, name, age, subject):
Person.__init__(self, name, age)
self.subject = subject
class Student(Person):
def __init__(self, name, age, grade):
Person.__init__(self, name, age)
self.grade = grade
Since a teacher and a student are both people, I can simply construct a parent class called Person with attributes that are common among all people, like age and name. Then, in the Teacher class, we need to know what subject that teacher teaches, but also by inheriting from the Person superclass, we can ensure that the teacher has a name and an age. And for students, a unique attribute may be what grade that student is in. So we first simply inherit from the superclass to ensure the student has a name and age, and then create a new attribute called grade in the constructor of the Student class.
Object-Oriented Programming is very intuitive and saves a programmer a lot of work in terms of writing efficient code.
No comments:
Post a Comment