© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
K. WilsonThe Absolute Beginner's Guide to Python Programminghttps://doi.org/10.1007/978-1-4842-8716-3_9

9. Object-Oriented Programming

Kevin Wilson1  
(1)
London, UK
 

Python is an object-oriented programming language. This means that the program design is based around objects, rather than functions and logic.

Each object is created using a blueprint known as a class . Each class has attributes to contain the data an object needs to work with.

Each class also contains functions, called methods that perform operations on objects.

An object is an instance of a class. So, you could have a class called “car” and use it to define an object called “merc.”

You’ll need the source files in the directory Chapter08.

Principles of OOP

The four principles of OOP are encapsulation, inheritance, polymorphism, and abstraction.

Encapsulation

With encapsulation , you restrict access to methods and attributes within a certain class. This prevents accidental modification of data and unwanted changes to other objects.

Inheritance

A class can inherit all the methods and attributes from another class. If a class called “person” had the attributes name, age, and dob, we could use this class to define two other child classes called “student” and “staff.” Both inherit the methods and attributes from the “person” class.

Polymorphism

Polymorphism allows us to define methods in the child class with the same name as defined in the parent class. This is known as method overriding.

Polymorphism also allows us to define methods that can take many forms.

Abstraction

Abstraction is the process of reducing objects to their essence so that only the necessary elements are represented. In other words, you remove all irrelevant information about an object in order to reduce its complexity.

Classes and Objects

You can define a class using the class keyword:
class <class-name> :
    <class attributes and methods>
Here, we have created a class called Person:
class Person :
All classes have a function called init () which is automatically executed when the class is initiated. Use the init () function to initialize attributes.
def   init   (self, name, dob, email):
     self.name = name
     self.dob = dob
     self.email = email

The self keyword represents the current instance of the class (i.e., the object created from the class). By using the self keyword, you can access the attributes of the object itself.

When you declare a method, you pass the current instance of the class (i.e., the object itself), along with any other parameters required, to the method:
def getAge(self):
    currentDate = date.today()
    age = currentDate.year - self.dob.year
    return age
When you need to use any attribute, you use self followed by the attribute name :
self.attribute-name
So, for example:
self.email

Let’s take a look at a program. Open the file class.py. Here, we’ve defined our “Person” class.

The python window with 15 lines of code calls the class Person followed by codes, defines the initializations, and defines class methods.

To create an object from the class, call the class Person(...) and pass any data using parenthesis ( ). Assign the new object to a variable, for example, person.

Five-line code to create an object from the class to call a person.

To use the object , use the dot notation:
classname.method()
or
classname.attribute

So in our example, to use the attributes we use the dot notation, with the object name followed by the attribute name as we can see here:

Two-line code to use attributes reads print, person dot name, and print, person dot email both in open and close parenthesis.

Similarly, if we want to use the methods of an object, we use the dot notation, with the object name followed by the method name as we can see here:

A line of code reads print, open parenthesis, person dot get age, open and close parenthesis, close parenthesis.

Class Inheritance

We mentioned earlier that inheritance means a class can inherit all the methods and attributes from another class.

As we can see in Figure 9-1, we have a parent or super class called Person and two child (or sub) classes called Student and Staff.

A branching diagram presents the interconnection of the parent class labeled person to its 2 subclasses, student and staff. Underneath each class are lines of codes.

Figure 9-1

How a class inherits properties from its parent

The child classes inherit all the attributes and methods of the parent classes. Child classes can include any additional attributes and methods that are not accessible from other classes.

To create a child class , declare the class as normal, except include the parent class in parenthesis after the class name. So
class child-class(parent-class):
If you want to inherit all the methods and properties from the parent, use super() :
super(). init (name, dob, email)

Open the file inherit.py. Here, we’ve created a class called person . We’ve also created two child classes called student and staff.

Python window with 37 lines of code that inherit the methods and properties from a parent class and add any methods for the child class.

We can create a lecturer object from the class Staff.

Six-line code for generating a lecturer object from the class staff.

To reference our attributes, we use the dot notation .

Two-line code to print attributes, lecturer name, and salary.

Polymorphic Classes

In this example, we’re going to create two classes. To be polymorphic , each of these classes needs to have an interface in common. So we define methods for each class that have the same name. In this case, we can define a method that calculates the area in each class (triangle, square, and circle as we can see in Figure 9-2).

A diagram depicts three squares labeled triangle, square, and circle, with two lines of code calculating the area of each shape.

Figure 9-2

An example of how classes can contain the same method

A branching diagram presents the polygon parent class with two child classes, triangle, and square below. An arrow compares a method in the child class overriding method in the parent class.

Figure 9-3

How a method in a child class can override the method defined in the parent class

Open the file polyclass.py. Here, we’ve defined a class for triangle, square, and circle. Notice each class has a method called getArea().

The Python window with 19 lines of code defines a class for triangle, square, and circle with a get area method for each class that returns data of measurements.

This means we can call the .getArea() method for each object created.

Three-line code to print the area of a square, triangle, and circle.

Method Overriding

With method overriding , you can define a method with the same name in the child class as in the parent class. The method in the child class overrides the method in its parent class.****

Have a look at methodoverride.py. Here, we’ve defined the classes discussed earlier. The methods in the child classes have the same name as in the parent class. Each method is redefined and specific to the class. Let’s see what happens when we create our objects and call the methods.

Eleven-line code that creates a triangle object, calls the get area method, creates a pentagon object and calls get area method for pentagon.

Give it a try .

Lab Exercises

  1. 1.

    Declare a new class called Vehicle without any attributes and methods.

     
  2. 2.

    Add some attributes to the Vehicle class such as

    Name

    Speed

    Mileage

     
  3. 3.

    Add a method to the Vehicle class to return the vehicle name.

     
  4. 4.

    Create a child class called Car that will inherit all the variables and methods of the Vehicle class.

     
  5. 5.

    Create a child class called Taxi.

     
  6. 6.

    Add a method to the Taxi class to collect the fair.

     

Summary

  • Python is an object-oriented programming language.

  • A class is a blueprint for an object.

  • Each class has attributes to contain the data an object needs to work with.

  • Each class contains functions, called methods that perform operations on objects.

  • Encapsulation restrict access to methods and attributes within a certain class.

  • A class can inherit all the methods and attributes from another class. Child classes inherit methods and attributes from the parent.

  • Polymorphism allows us to define methods in the child class with the same name as defined in the parent class.

  • Abstraction is the process of reducing objects to their essence so that only the necessary elements are represented.

  • You can define a class using the class keyword.

  • To use methods defined in an object, use the dot notation.

  • Method overriding allows you to define a method with the same name in the child class as in the parent class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.20.193