Attributes (OOP) (OCR A-Level Computer Science): Revision Notes
Attributes (OOP)
Overview
In Object-Oriented Programming (OOP), attributes are variables that store data specific to each instance of a class. They represent the state of an object, holding values that define its unique characteristics. Attributes can be either public or private, which affects how they can be accessed and modified. Understanding attributes is essential for implementing data security, modularity, and flexibility in OOP.
Types of Attributes
Public Attributes
- Definition: Public attributes can be accessed and modified directly from outside the class. They are often used for values that do not need any control over access or modification.
- Accessing: These attributes are accessible using dot notation on an object of the class.
- Drawbacks: Public attributes can lead to unintended modifications, as they can be changed from outside the class without restrictions.
Example:
class Car:
def __init__(self, colour):
self.colour = colour # Public attribute
car1 = Car("red")
print(car1.colour) # Outputs: red
car1.colour = "blue" # Directly modify the colour
Private Attributes
- Definition: Private attributes are restricted and can only be accessed or modified from within the class itself. In Python, private attributes are usually indicated by a single underscore (
_) or a double underscore (__) before the attribute name. - Encapsulation: Private attributes support the principle of encapsulation, which restricts direct access to an object's data. Encapsulation protects the data by controlling how it is accessed and modified.
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
account = BankAccount(100)
# print(account.__balance) # Error: Attribute is not directly accessible
Using Get and Set Methods (Accessors and Mutators)
Since private attributes cannot be accessed directly from outside the class, getter and setter methods (also known as accessors and mutators) are used to control access and modification.
Getter Methods (Accessors)
Purpose: Getter methods allow external code to access the value of a private attribute without directly exposing it. This enables controlled and secure data retrieval.
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def get_balance(self):
return self.__balance # Accessor method to retrieve balance
account = BankAccount(100)
print(account.get_balance()) # Outputs: 100
Setter Methods (Mutators)
Purpose: Setter methods allow external code to modify the value of a private attribute, with any necessary validation or restrictions applied within the method. This helps enforce data integrity.
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def set_balance(self, amount):
if amount >= 0: # Only allow non-negative balance
self.__balance = amount
else:
print("Invalid amount: Balance cannot be negative.")
account = BankAccount(100)
account.set_balance(200) # Sets balance to 200
print(account.get_balance()) # Outputs: 200
account.set_balance(-50) # Error: Invalid amount
Attributes Example
Bank Account Class with Private Attributes and Get/Set Methods
Below is a complete example illustrating the use of private attributes and getter/setter methods to control access to an account balance.
class BankAccount:
def __init__(self, account_holder, balance=0):
self.account_holder = account_holder # Public attribute
self.__balance = balance # Private attribute
# Getter for balance
def get_balance(self):
return self.__balance
# Setter for balance with validation
def set_balance(self, amount):
if amount >= 0:
self.__balance = amount
else:
print("Error: Balance cannot be negative.")
# Additional method to deposit funds
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"${amount} deposited. New balance: ${self.__balance}")
else:
print("Error: Deposit amount must be positive.")
Explanation of the Example
- Encapsulation: The __balance attribute is private, protecting it from direct access.
- Getter Method: get_balance allows controlled access to the balance.
- Setter Method: set_balance validates that the balance is non-negative before updating.
- Public Attribute: account_holder is public, so it can be accessed directly since it does not need control or validation.
Benefits of Using Private Attributes and Get/Set Methods
- Data Security: Private attributes ensure data is not modified unintentionally or inappropriately, supporting secure data handling.
- Data Integrity: Setter methods can validate data before modifying attributes, and maintaining correct values.
- Encapsulation: Getters and setters protect and control access to sensitive data, keeping the internal representation hidden from outside code.
Note Summary
Common Errors with Attributes
- Incorrect Use of self: Forgetting to use self to refer to an attribute within a class method can cause an error.
- Modifying Private Attributes Directly: Trying to access or modify private attributes directly outside of their class will result in an error.
- Lack of Validation: Without validation in setters, attributes can be set to inappropriate values, potentially leading to bugs or crashes.
Key Takeaways
- Public attributes are directly accessible from outside the class, suitable for data that doesn't require access restrictions.
- Private attributes are restricted to internal access only, promoting encapsulation and data security.
- Getter and Setter methods allow controlled access and modification of private attributes, supporting data integrity and proper data management.
- Using private attributes with get/set methods is a key part of maintaining data integrity and modularity in OOP.