Computer Science
Grade 9
20 min
Getters and Setters: Controlling Access to Attributes
Understand how to use getters and setters to control access to and modification of object attributes.
Tutorial Preview
1
Introduction & Learning Objectives
Learning Objectives
Define encapsulation and explain its importance in protecting data.
Differentiate between public and private attributes.
Implement a getter method to safely retrieve the value of a private attribute.
Implement a setter method to safely modify the value of a private attribute.
Add validation logic within a setter method to ensure data integrity.
Refactor a simple class to use private attributes with public getters and setters instead of directly accessible public attributes.
Ever wonder why you need a password to see your bank balance online instead of just looking it up? 🏦 Let's find out how programming uses a similar idea to protect important data!
In this lesson, you'll learn how to protect the data inside your objects using special methods...
2
Key Concepts & Vocabulary
TermDefinitionExample
EncapsulationThe practice of bundling data (attributes) and the methods that work on that data within a single unit (a class). It also involves hiding the internal state of an object from the outside.A `GamePlayer` class holds the `_health` data and the `take_damage()` method together. The outside world can't directly set `_health` to -50; it must use the `take_damage()` method.
AttributeA variable that belongs to an object and holds a piece of data about that object.In a `Student` object, `name` and `student_id` would be attributes.
Private AttributeAn attribute that should only be accessed or changed by methods within its own class. In many languages like Python, this is indicated by a leading underscore.A `_balance` attribute in a `BankAccount` class. The und...
3
Core Syntax & Patterns
Getter Method Pattern
def get_attribute_name(self):
return self._private_attribute
Use this pattern to create a public method that reads and returns the value of a private attribute. The method name almost always starts with 'get_' followed by the attribute name.
Setter Method Pattern with Validation
def set_attribute_name(self, new_value):
if [condition is met]:
self._private_attribute = new_value
else:
print("Invalid value!")
Use this pattern to create a public method that updates a private attribute. It is the perfect place to add `if` statements to check if the `new_value` is valid before making the change.
Private Attribute Naming Convention
_attribute_name
In Python and some other languages, a single leading under...
4 more steps in this tutorial
Sign up free to access the complete tutorial with worked examples and practice.
Sign Up Free to ContinueSample Practice Questions
Challenging
You are designing a `BankAccount` class with a private `_balance` attribute. Which setter method, `set_balance(self, amount)`, correctly handles a deposit (positive amount) and a withdrawal (negative amount) while preventing the balance from ever going below zero?
A.def set_balance(self, amount):
if amount > 0:
self._balance += amount
B.def set_balance(self, amount):
self._balance += amount
C.def set_balance(self, amount):
if self._balance + amount >= 0:
self._balance += amount
else:
print("Insufficient funds!")
D.def set_balance(self, amount):
if amount < self._balance:
self._balance += amount
Challenging
A `Student` class has `_grade_level` (9, 10, 11, or 12). The rule is that a student can only advance one grade at a time (e.g., 9 to 10). Which `set_grade_level` setter correctly enforces this 'promotion' rule?
A.def set_grade_level(self, new_grade):
if new_grade > self._grade_level:
self._grade_level = new_grade
B.def set_grade_level(self, new_grade):
if new_grade == self._grade_level + 1 and new_grade <= 12:
self._grade_level = new_grade
C.def set_grade_level(self, new_grade):
if new_grade in [9, 10, 11, 12]:
self._grade_level = new_grade
D.def set_grade_level(self, new_grade):
if new_grade > 0:
self._grade_level = new_grade
Challenging
How would you implement a 'read-only' attribute, such as a unique `_serial_number` that is set once when an object is created and should never be changed afterwards?
A.Make the attribute public so everyone can see it.
B.Provide a public setter but no getter.
C.Provide both a public getter and a public setter, but add a comment not to use the setter.
D.Provide a public getter, but do not provide a public setter.
Want to practice and check your answers?
Sign up to access all questions with instant feedback, explanations, and progress tracking.
Start Practicing Free