Object-Oriented Programming

Object-Oriented Programming#

Object-Oriented Programming (OOP) is a programming paradigm, which means that it is an approach to writing and structuring programs.

In OOP we program add the concept of objects. In the programming fundamentals module we focused on procedural programming where we constructed programs using only functions and procedures.

Whether you use OOP or not will depend on the problem you’re trying to solve but may also come down to personal preference.

Note

Object-Oriented Programming is not mutually exclusive with procedural programming. In Python, we can use both ideas in the same program.

Classes#

A class is the type of an object. The class definition specifies the attributes (properties) and methods (behaviours). Think of a class as a blueprint, from which we will make real objects.

Example: Account

You can see there are placeholders for the BSB number, account number, balance and holder name attributes. This class also has the methods deposit, withdraw and calculate interest.

../../_images/blank_bank_account_full.png

Instances#

An instance is a specific realisation of the class that has actual values assigned to the attributes.

In the example, we have created two instances of the Account class. One for Bruce Wayne and one for Clark Kent.

../../_images/instances_account_full.png

Abstraction#

../../_images/abstraction2.png

Classes and objects allow programmers to abstract the implementation details of an object by defining methods. When using methods, one does not need to know how exactly the object is managing its internal state. This allows programmers to focus on what it can do rather than how implements its functionality.

Encapsulation#

../../_images/encapsulation.png

Bundling attributes and behaviours into a single class and individual instances is called encapsulation. In other words, objects create a barrier between their internal state and other parts of the code, which helps maintain data integrity and creates more modular code.

Objects can be treated by programmers as isolated units, that can be stored as variables and interacted with independently.