Methods (OOP) (OCR A-Level Computer Science): Revision Notes
📚 Revision Notes
Methods (OOP)
Overview
In Object-Oriented Programming (OOP), methods are functions defined within a class that represent the behaviours of an object. They can manipulate an object's attributes and perform actions associated with the class. Like attributes, methods can be public or private, determining their accessibility within and outside of the class. Understanding methods, and the distinction between public and private methods, is essential for effective OOP.
Types of Methods
Public Methods
- Definition: Public methods are accessible from outside the class, allowing interaction with an object's functionality. These methods define the primary behaviours of the class that other parts of the programme can use.
- Purpose: Public methods serve as the primary interface of a class, allowing external code to interact with an object in a controlled way.
- Benefits:
- Access and Interaction: Public methods provide controlled access to an object's functionality.
- Encapsulation: They allow access to data and operations without exposing the internal workings of the class.
lightbulbExample
Example:
class Calculator:
def add(self, a, b):
return a + b # Public method accessible from outside the class
calc = Calculator()
print(calc.add(3, 5)) # Outputs: 8
Private Methods
- Definition: Private methods are intended for internal use only, usually marked by a leading underscore (e.g., _method_name) in Python. These methods cannot be accessed directly from outside the class.
- Purpose: Private methods perform auxiliary or supportive tasks within the class. They often help break down complex processes and support the functionality of public methods without being exposed to the rest of the programme.
- Benefits:
- Encapsulation and Security: Private methods help keep implementation details hidden, ensuring that only the necessary interface is exposed.
- Modularity and Maintenance: Private methods can simplify complex tasks within the class, making code more modular and easier to maintain.
lightbulbExample
Example:
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
self._log_transaction(amount) # Calls private method
def _log_transaction(self, amount): # Private method
print(f"Transaction: Deposited ${amount}. New balance: ${self.balance}")
account = BankAccount()
account.deposit(100) # Outputs: Transaction: Deposited $100. New balance: $100
# account._log_transaction(50) # Error: Cannot directly access private method
Example: Bank Account Class with Public and Private Methods
infoNote
Below is an example illustrating the use of public and private methods in a BankAccount class.
class BankAccount:
def __init__(self, account_holder, balance=0):
self.account_holder = account_holder
self.balance = balance
# Public method for depositing money
def deposit(self, amount):
if amount > 0:
self.balance += amount
self._log_transaction("deposit", amount)
# Public method for withdrawing money
def withdraw(self, amount):
if amount > 0 and amount <= self.balance:
self.balance -= amount
self._log_transaction("withdrawal", amount)
else:
print("Insufficient funds or invalid amount.")
# Public method to check balance
def check_balance(self):
return self.balance
# Private method to log transactions
def _log_transaction(self, transaction_type, amount):
print(f"{transaction_type.capitalise()} of ${amount}. New balance: ${self.balance}")
Explanation of the Example
- Public Methods:
- deposit and withdraw are public methods that allow depositing and withdrawing funds, respectively.
- check_balance is also public, providing access to the current balance.
- Private Method:
- _log_transaction is a private method used internally to log transaction details after every deposit or withdrawal. This method is not meant to be called directly from outside the class.
Key Points for Tracing and Writing Code with Methods
- Public Methods: These can be tested and called directly from outside the class. In the above example, deposit, withdraw, and check_balance provide controlled access to the bank account's functionality.
- Private Methods: Ensure that private methods are only used within the class. They provide essential internal operations, helping to keep the main logic of public methods clean and manageable.
Benefits of Using Public and Private Methods
- Data Security: Private methods help protect the internal processes of the class, promoting encapsulation.
- Code Readability: Public methods present a clear interface for external code, while private methods help organise complex processes within the class.
- Modular Design: By segmenting complex actions into smaller, private methods, the class remains modular and easy to maintain.
Note Summary
infoNote
Common Errors with Methods
- Accessing Private Methods from Outside: Attempting to directly access private methods (like _log_transaction in the example) from outside the class will raise an error. Private methods are intended for internal use only.
- Inconsistent Naming: In Python, private methods should start with a single underscore to signal restricted access. Not following this convention can lead to unintended access.
- Directly Modifying Attributes Instead of Using Methods: It's generally better to interact with an object through its public methods rather than modifying its attributes directly, as methods can include validation and additional functionality.
infoNote
Key Takeaways
- Public Methods: Accessible from outside the class, defining how an object's functionality is exposed to other parts of the programme.
- Private Methods: Restricted to internal use within the class, supporting complex actions while keeping implementation details hidden.
- Encapsulation: Using public and private methods maintains encapsulation, ensuring a clear interface and protecting internal operations.