Object-Oriented Programming (OOP) Basics
9 min read
Object-Oriented Programming (OOP) Basics π»
Welcome to the fascinating world of Object-Oriented Programming (OOP) in Python! Before we dive in, let's understand the "why."
The Problem π€
Imagine you're building a complex application, say, a system to manage a library. You'd need to keep track of books, members, and their borrowing records. With the programming knowledge you might have now (variables, lists, functions), you could use separate lists for book titles, another for authors, and yet another for their availability status. You would then have functions like borrow_book(), return_book(), etc., that take these lists as arguments and modify them.
This can get messy, fast! π€― What if you need to add more properties to a book, like its genre or publication year? You'd have to modify every single function that deals with books. It's like having all your car's parts (engine, wheels, seats) scattered on the garage floor instead of assembled into a functional vehicle. This is where OOP comes to the rescue.
The Solution: Object-Oriented Programming π‘
OOP allows us to bundle related data and the functions that operate on that data into a single unit called an object. Instead of a loose collection of variables and functions, you create a "Book" blueprint that defines what a book is and what it can do.
1. Classes and Objects: Blueprints and Instances π
Let's start with the absolute fundamentals: classes and objects.
Definition: A class is a blueprint for creating objects. It defines a set of attributes (data) and methods (functions) that the created objects will have. An object is an instance of a class; it's a concrete entity created from the class blueprint.
Think of it this way: a car's engineering blueprint is the class. It details all the specifications: engine type, number of doors, color options. The actual cars rolling off the assembly line are the objects (or instances) of that blueprint. Each car shares the same fundamental design but has its own specific state (one is red, another is blue; one has 10 miles on it, another has 50,000).
In Python, we define a class using the class keyword.
Syntax:
class ClassName:
# class body
passBy convention, class names in Python start with a capital letter (PascalCase). The pass keyword is a placeholder that means "do nothing."
Example:
Let's create a simple blueprint for a Dog.
class Dog:
passThat's it! We've created a class named Dog. It doesn't do much yet, but it's a valid blueprint. Now, let's create some actual dogs (objects) from this blueprint. Creating an object from a class is called instantiation.
# Creating instances (objects) of the Dog class
dog1 = Dog()
dog2 = Dog()
print(dog1)
print(dog2)Output:
<__main__.Dog object at 0x000001>
<__main__.Dog object at 0x000002>The output shows that dog1 and dog2 are two distinct Dog objects, located at different memory addresses. They are separate instances of the same class.
Right now, our dogs are pretty boring. They don't have names, breeds, or any behaviors. Let's fix that.
2. The __init__ Method and Instance Attributes π οΈ
The Problem: How do we give each object its own unique data when it's created? We need a way to initialize our objects with their own set of attributes.
The __init__ Method: Python has a special method called __init__ (short for "initialize"). This method is automatically called whenever you create a new instance of a class. It's the perfect place to set up the initial state of our objects. Methods that start and end with double underscores are often called "dunder" methods (for double underscore).
Instance Attributes: These are variables that belong to a specific instance of a class. Each object can have its own values for these attributes.
Let's give our Dog class some instance attributes.
Example:
class Dog:
def __init__(self, name, breed, age):
self.name = name
self.breed = breed
self.age = age
print(f"A new dog named {self.name} has been created!")
# Creating instances with initial attributes
dog1 = Dog("Buddy", "Golden Retriever", 3)
dog2 = Dog("Lucy", "Poodle", 5)
# Accessing instance attributes
print(f"{dog1.name} is a {dog1.age}-year-old {dog1.breed}.")
print(f"{dog2.name} is a {dog2.age}-year-old {dog2.breed}.")Output:
A new dog named Buddy has been created!
A new dog named Lucy has been created!
Buddy is a 3-year-old Golden Retriever.
Lucy is a 5-year-old Poodle.What's happening here?
def __init__(self, name, breed, age):: We define the initializer. The first parameter of any instance method is alwaysself.self: Theselfparameter is a reference to the current instance of the class. It's how the object keeps track of its own data. When you calldog1 = Dog(...), Python creates an emptyDogobject and then calls the__init__method, passing that new object as theselfargument.self.name = name: We are creating an instance attribute callednameand assigning the value of thenameparameter to it.self.nameis different fordog1anddog2.
A fun fact! The self parameter doesn't have to be named self. You could technically name it whatever you want. However, it is a very strong convention in the Python community to use self, and you should always stick to it to avoid confusing others (and your future self!).
3. Class Methods vs. Instance Methods βοΈ
Now that our objects have data (attributes), let's give them some behaviors (methods).
Definition:
- Instance Methods: These are the most common type of methods. They operate on an instance of the class and have access to the instance's data through the
selfparameter. - Class Methods: These methods are bound to the class and not the instance. They don't have access to instance-specific data (
self). Instead, they take aclsparameter that points to the class itself.
Instance Methods in Action:
Let's add a bark method to our Dog class.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
# This is an instance method
def bark(self):
return f"{self.name} says Woof!"
my_dog = Dog("Rex", "German Shepherd")
print(my_dog.bark())Output:
Rex says Woof!The bark method uses self.name to access the name of the specific dog instance that is barking.
When to use Class Methods?
Class methods are often used for factory functions that create instances of the class in a different way. Imagine you want to create a Dog object from a birth year instead of an age.
Example:
To define a class method, we use the @classmethod decorator.
import datetime
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
# Instance method
def bark(self):
return f"{self.name} says Woof!"
# Class method
@classmethod
def from_birth_year(cls, name, birth_year):
current_year = datetime.date.today().year
age = current_year - birth_year
return cls(name, age) # 'cls' is used to create an instance of the class
# Creating instances
dog1 = Dog("Buddy", 4)
dog2 = Dog.from_birth_year("Lucy", 2020)
print(f"{dog1.name} is {dog1.age} years old.")
print(f"{dog2.name} is {dog2.age} years old.")Output:
Buddy is 4 years old.
Lucy is 6 years old.Here, from_birth_year is a class method. It doesn't know about any specific dog; instead, it knows about the Dog class itself (via cls). It performs a calculation and then uses cls(name, age) to create and return a new instance of the Dog class.
4. Encapsulation: Public and Private Attributes π
The Problem: Sometimes, you have attributes or methods in your class that are for internal use only. You don't want someone using your class to accidentally modify them, as it could break things.
Encapsulation: This is the principle of bundling the data (attributes) and the methods that operate on the data into a single unit (the class). It also involves restricting direct access to some of an object's components. This is a key concept for preventing accidental data modification.
Public Attributes: By default, all attributes and methods in a Python class are public. This means they can be accessed from outside the class.
class Car:
def __init__(self, make, model):
self.make = make # Public attribute
self.model = model # Public attribute
my_car = Car("Toyota", "Corolla")
print(my_car.make) # Accessing a public attribute
my_car.make = "Honda" # Modifying a public attribute
print(my_car.make)Output:
Toyota
HondaPrivate Attributes: In many other languages, you have a private keyword. Python's approach is a bit different and based on convention. To indicate that an attribute should be treated as "private" (meaning it's for internal use), you prefix its name with a single underscore _.
Example with a "Private" attribute:
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self._balance = balance # "Private" attribute
def deposit(self, amount):
if amount > 0:
self._balance += amount
print(f"Deposited ${amount}. New balance: ${self._balance}")
def withdraw(self, amount):
if 0 < amount <= self._balance:
self._balance -= amount
print(f"Withdrew ${amount}. New balance: ${self._balance}")
else:
print("Invalid withdrawal amount or insufficient funds.")
def get_balance(self):
return f"Current balance for {self.owner}: ${self._balance}"
my_account = BankAccount("John Doe", 1000)
print(my_account.get_balance())
my_account.deposit(500)
# You can still access it, but the underscore is a warning: "Don't touch!"
# print(my_account._balance) # This is considered bad practice.Output:
Current balance for John Doe: $1000
Deposited $500. New balance: $1500This single underscore is a convention. It doesn't actually prevent you from accessing the attribute, but it signals to other developers that they shouldn't access it directly.
Name Mangling with Double Underscore:
If you want to make it harder to access an attribute, you can use a double underscore __. This is a feature called name mangling.
class MyClass:
def __init__(self):
self.__super_private_variable = "You can't see me!"
obj = MyClass()
# print(obj.__super_private_variable) # This will raise an AttributeErrorWhen you try to run this, you'll get an error. Python changes the name of the attribute to _ClassName__attributeName. So you could technically still access it via obj._MyClass__super_private_variable, but it's a strong indicator that you really shouldn't. This is useful to avoid naming conflicts in inheritance, a topic for another day!
For most day-to-day coding, the single underscore _ convention is what you'll see and use for encapsulation.
Further Reading π
- Official Python Documentation on Classes: https://docs.python.org/3/tutorial/classes.html
- Real Python - Object-Oriented Programming (OOP) in Python 3: https://realpython.com/python3-object-oriented-programming/
- GeeksforGeeks - Python Classes and Objects: https://www.geeksforgeeks.org/python-classes-and-objects/
Challenge
Your task is to model a simple banking system using Object-Oriented Programming in Python.
Create a class named BankAccount that encapsulates the properties and behaviors of a bank account.
Requirements:
Constructor (
__init__): The class constructor should initialize a new account with anowner_name, a uniqueaccount_number, and aninitial_balance. The balance itself should be stored in an attribute that is conventionally marked for internal use only (i.e., 'private').Instance Methods:
deposit(self, amount): A method to add a specifiedamountto the account's balance.withdraw(self, amount): A method to subtract a specifiedamountfrom the balance. This method must include logic to prevent the balance from dropping below zero. If an attempted withdrawal exceeds the available funds, the balance should not change.get_balance(self): A method that returns the current value of the account's balance.
Class Method:
- Implement a class method named
create_premium_account(cls, owner_name). This method should function as a factory to create a specific type of account. It should return a newBankAccountinstance initialized with a starting balance of1500and a standardized account number string formatted asf"PREMIUM-{owner_name.upper()}". This method must be appropriately decorated to function as a class method.
- Implement a class method named
Expected result
Your submission should be a single Python class definition for BankAccount that fulfills all the requirements.
- The class must be named
BankAccount. - The
__init__method must correctly initializeowner_name,account_number, and a private attribute for the balance (e.g.,_balance). - It must contain the three specified instance methods:
deposit,withdraw, andget_balance. - The
withdrawmethod must contain the logic to prevent a negative balance. - It must include a class method named
create_premium_accountthat is correctly decorated with@classmethodand returns a newBankAccountinstance with the specified default values.