Enhance your Python OOP skills with this fill-in-the-blanks quiz on encapsulation. Ideal for students, beginners, and those preparing for interviews. Learn with Yasir Bhutta and reinforce your understanding of access modifiers, getter/setter methods, and more.
protected
A single underscore suggests the variable is for internal use, but Python doesn't enforce this restriction.
mangling
Name mangling changes the variable name to `_ClassName__variable` to avoid naming conflicts in subclasses.
protect
Encapsulation prevents direct access to an object's internal state, requiring controlled access through methods.
setter
Setter methods allow controlled modification of private attributes with validation logic.
getter
The `@property` decorator creates a getter method that's called when accessing the attribute.
age
The setter decorator must match the property name (e.g., `@age.setter` for a property named 'age').
hasattr()
`hasattr(obj, 'attribute')` returns True if the object has the specified attribute.
@property
Using `@property` without a setter creates a read-only attribute.
__var
Name-mangled variables can be accessed externally using `_ClassName__variablename` format.
abstraction
The four main OOP principles are encapsulation, abstraction, inheritance, and polymorphism.
class BankAccount:
def __init__(self, balance):
self._balance = balance
def get_balance(self):
return self._balance
protected
A single underscore is a naming convention indicating protected (internal-use) members.
class Temperature:
def __init__(self):
self.__celsius = 0
@property
def celsius(self):
return self.__celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Temperature too low")
self.__celsius = value
controlled
Properties provide controlled access to private attributes with validation logic.
class Student:
def __init__(self, name):
self.__name = name
def get_name(self):
return self.__name
def set_name(self, new_name):
if len(new_name) < 2:
raise ValueError("Name too short")
self.__name = new_name
getter/setter methods
Getter/setter methods enforce validation while hiding implementation details.
class SecretVault:
def __init__(self):
self.__password = "12345"
vault = SecretVault()
# This will print the mangled name
print(dir(vault))
mangling
Name mangling changes the attribute name to `_SecretVault__password`.
class Smartphone:
def __init__(self):
self.__imei = "1234567890"
@property
def imei(self):
return "ACCESS DENIED"
read-only
By not providing a setter, the property becomes read-only.
class Employee:
def __init__(self, salary):
self._salary = salary
def _calculate_bonus(self):
return self._salary * 0.1
protected
Single underscore prefix indicates protected members (internal API).
class GameCharacter:
def __init__(self):
self.__health = 100
def take_damage(self, amount):
self.__health = max(0, self.__health - amount)
hidden
Double underscore prefix makes it harder to access directly (name mangling).