Object-oriented programming (OOP) is a programming paradigm that uses
"objects" to design applications and software. These objects are instances of
classes, which are essentially user-defined data types that encapsulate data and
behavior. By using objects, we can write code that is more modular, reusable, and
easier to understand.
Here's an example of how OOP works in Python. Let's say we want to create a
class to represent a bank account. We might define the class like this:
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds")
else:
self.balance -= amount
return self.balance
This class has three methods: __init__, deposit, and withdraw.
The __init__ method is a special method that is called when a new instance of the
class is created. It takes one argument, balance, which is the initial balance of the
account.
The deposit method takes one argument, amount, which is the amount to deposit.
It adds the amount to the balance and returns the new balance.
The withdraw method takes one argument, amount, which is the amount to
withdraw. If the amount is greater than the balance, it prints an error message.
Otherwise, it subtracts the amount from the balance and returns the new balance.