Skip to content
PythonObject-Oriented Programmingbeginner25 min read

Encapsulation and Properties

Understand public and non-public attributes, encapsulation conventions, properties, validation, and controlled attribute access in Python.

In this lesson, you will learn

  • ✓Explain encapsulation and the difference between public, non-public, and name-mangled attributes.
  • ✓Understand why a leading underscore is a convention rather than strict access control.
  • ✓Create properties with @property to expose methods through attribute-style access.
  • ✓Use property setters to validate values before updating object state.
  • ✓Distinguish read-only properties from writable properties.
  • ✓Choose between a normal attribute, a property, and a method for a clear class interface.

1. Understanding encapsulation and attribute visibility

Encapsulation means keeping related data and behavior together and providing a clear interface through which other code interacts with an object. It helps a class protect its intended rules, reduce accidental misuse, and make implementation details easier to change.

In Python, attributes are commonly described as public, non-public, or name-mangled. These terms describe naming conventions and language behavior; they are not three equivalent levels of strict access control.

A public attribute has an ordinary name, such as name or balance. It is intended to be part of the class's usable interface, so code outside the class can access it directly.

A name beginning with one underscore, such as _balance, signals that the attribute is intended for internal use. This is a convention: Python does not prevent outside code from accessing or changing _balance.

A name beginning with two leading underscores, such as __balance, is subject to name mangling when defined in a class. Python transforms the name using the class name to reduce accidental name clashes in subclasses. Name mangling is not a security mechanism and does not make data truly private.

Use public names for attributes intended for normal use. Use a leading underscore for implementation details that callers should generally avoid depending on. Reserve double-leading-underscore names for cases where avoiding subclass name collisions is useful, rather than using them automatically for every attribute.

Public and non-public attributes

Public and non-public attributes
python
class Student:
def __init__(self, name, marks):
self.name = name
self._marks = marks
 
student = Student('Asha', 85)
print(student.name)
print(student._marks)
Output
Asha 85

self.name is a public attribute intended to be accessed directly. self._marks begins with one underscore, signaling that it is intended for internal use. Python still allows student._marks to be accessed. The underscore communicates a convention; it does not block access. In a well-designed class, callers should generally use the documented interface rather than depending on implementation details such as _marks.

Note

Python does not provide a Java-style private keyword for ordinary instance attributes. A leading underscore communicates intended usage, while double-leading underscores trigger name mangling.

2. Why properties are useful

A property allows a method to be accessed using attribute-style syntax. Instead of requiring callers to write object.get_value(), a property can let them write object.value.

The @property decorator marks a method as the getter for a managed attribute. The getter runs when code reads that attribute.

A property is useful when reading an attribute requires a calculation, when access should be read-only, or when a class needs to validate changes to an attribute.

A property can also help a class evolve. For example, an attribute that initially returns a stored value could later calculate that value from other data without changing the syntax used by callers.

A property does not automatically make an object immutable or validate every possible internal change. The behavior depends on the getter, setter, deleter, and other code that can access the object's state.

Use properties when attribute-style access makes the interface clearer. Use an ordinary method when the operation performs a more substantial action, requires meaningful arguments, or has side effects that should be explicit.

Create a read-only property

Create a read-only property
python
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
 
@property
def celsius(self):
return self._celsius
 
t = Temperature(25)
print(t.celsius)
Output
25

The constructor stores the temperature in _celsius. The @property decorator turns celsius() into a property getter. The expression t.celsius calls the getter. It does not require parentheses. The getter returns the stored value, 25, which print() displays. Because no setter is defined, assigning t.celsius = 30 raises AttributeError under normal property behavior.

Note

A property is an interface, not a guarantee of security. Its getter and setter determine what happens during normal property access.

3. Property setters and validation

A property setter controls what happens when code assigns a value to a property. It is defined by decorating another method with @property_name.setter.

The getter and setter share the same public property name. For example, @property defines temperature, and @temperature.setter defines how assignments to temperature are handled.

The setter receives the assigned value as an argument. It can check whether that value is valid before updating the underlying attribute.

If a value violates the class's rules, the setter can raise an exception such as ValueError. This prevents normal property assignment from silently accepting an invalid value.

Inside the setter, assign the validated value to a separate backing attribute such as _temperature. Do not assign it back to self.temperature, because that would call the setter again and cause infinite recursion.

A setter validates only assignments that pass through that property. Code that directly changes the backing attribute can bypass the setter, which is another reason the leading underscore convention matters.

Validate a temperature before storing it

Validate a temperature before storing it
python
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
 
@property
def celsius(self):
return self._celsius
 
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError('Temperature cannot be below absolute zero.')
self._celsius = value
 
t = Temperature(25)
t.celsius = 30
print(t.celsius)
Output
30

The constructor assigns self.celsius, which invokes the setter. The setter checks whether the supplied value is below -273.15 degrees Celsius. Because 25 is valid, the setter stores it in _celsius. The later assignment t.celsius = 30 invokes the same setter and stores 30. Reading t.celsius invokes the getter, which returns 30. If an assignment used a value below -273.15, the setter would raise ValueError before changing _celsius.

Caution

Avoid recursive property setters. Inside @value.setter, use self._value = value rather than self.value = value. The latter invokes the setter again instead of storing the value.

4. Read-only properties and controlled updates

A read-only property defines a getter but no setter. Code can read the property through the normal interface but cannot assign a new value to it through that property.

Read-only does not mean that the underlying object can never change. Other methods may update internal state, and mutable objects returned by a property may still be modified through their own interfaces.

Sometimes a class needs controlled updates rather than unrestricted assignment. A setter is suitable when assigning a value is natural and the new value can be validated. A method is often better when the operation represents an action such as depositing money or withdrawing money.

For a bank account, a balance property can expose the current balance without allowing ordinary assignment through the balance property. Separate deposit() and withdraw() methods can express the permitted state changes.

The class should check the rules for each update before changing its state. For example, a withdrawal should not reduce the balance below zero if overdrafts are not allowed.

These interfaces discourage accidental misuse, but they do not create a security boundary. Python code can deliberately access implementation details, so this design is about reliable interfaces and maintainability rather than protection from hostile code.

Expose balance as a read-only property

Expose balance as a read-only property
python
class BankAccount:
def __init__(self, initial_balance=0):
if initial_balance < 0:
raise ValueError('Initial balance cannot be negative.')
self._balance = initial_balance
 
@property
def balance(self):
return self._balance
 
def deposit(self, amount):
if amount <= 0:
raise ValueError('Deposit must be positive.')
self._balance += amount
 
def withdraw(self, amount):
if amount <= 0:
raise ValueError('Withdrawal must be positive.')
if amount > self._balance:
raise ValueError('Insufficient funds.')
self._balance -= amount
 
account = BankAccount(100)
account.deposit(50)
account.withdraw(30)
print(account.balance)
Output
120

The account starts with a balance of 100. deposit(50) increases the balance to 150. withdraw(30) decreases the balance to 120. The balance property exposes the current balance without defining a public setter. The final print displays 120. Attempting account.balance = 500 would raise AttributeError because the property has no setter. The internal _balance attribute remains accessible by convention, not by a strict access restriction.

Note

Use a read-only property for information callers should read through the public interface. Use methods for meaningful state-changing operations that need clear names and explicit behavior.

5. Common mistakes, edge cases, and good design

The most common property mistake is confusing the public property with its backing attribute. A property named balance can use _balance for storage. This separation allows the getter and setter to control normal access.

Another common mistake is assuming that _balance is inaccessible from outside the class. The underscore is a signal to callers, not an access-control mechanism.

A getter should normally return the value it represents. Forgetting return means the getter returns None, even if it calculates the correct value internally.

Validation should match the actual requirements. If a score must be between 0 and 100, check both limits. If a value must be numeric, consider how non-numeric values should be handled rather than assuming every caller provides the correct type.

A setter that raises an exception before updating the backing attribute leaves that attribute unchanged for that assignment. This is important when maintaining valid object state.

Properties should usually be lightweight. A getter that performs slow network calls, writes files, or changes unrelated state can surprise callers because property access looks like a simple attribute read.

Do not add a property merely to make a simple attribute look sophisticated. A regular public attribute is often appropriate when no validation, calculation, or compatibility behavior is needed.

For numeric properties, remember that Python's bool type is a subclass of int. If a requirement specifically excludes booleans, checking only isinstance(value, int) is not sufficient. Likewise, floating-point comparisons and non-finite values may require extra care in applications that depend on numerical accuracy.

Encapsulation is most effective when a class documents its intended interface and keeps its invariants consistent across constructors, setters, and state-changing methods.

Reject invalid input without overwriting the previous value

Reject invalid input without overwriting the previous value
python
class Score:
def __init__(self, value):
self.value = value
 
@property
def value(self):
return self._value
 
@value.setter
def value(self, new_value):
if not 0 <= new_value <= 100:
raise ValueError('Score must be between 0 and 100.')
self._value = new_value
 
score = Score(80)
try:
score.value = 110
except ValueError:
print(score.value)
Output
80

The constructor initializes the score to 80 through the property setter. The assignment of 110 invokes the setter and fails validation. The setter raises ValueError before assigning to _value. The except block handles that ValueError. The stored score is still 80, so the final print displays 80.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Believing that a leading underscore makes an attribute private.

Why it happens: A leading underscore is a convention indicating non-public use; Python does not enforce private access for such attributes.

Incorrect Approach
script.py
python
Believing that a leading underscore makes an attribute private.
Correct Solution
script.py
python
Treat _attribute as a non-public naming convention. Python still permits direct access.

Key takeaway: Treat _attribute as a non-public naming convention. Python still permits direct access.

#2 Using self.value = value inside the value setter.

Why it happens: Assigning self.value inside the value setter calls the same setter again, causing recursion; store the value under a separate backing attribute such as self._value.

Incorrect Approach
script.py
python
Using self.value = value inside the value setter.
Correct Solution
script.py
python
Store the validated value in a separate backing attribute, such as self._value, to avoid recursively calling the setter.

Key takeaway: Store the validated value in a separate backing attribute, such as self._value, to avoid recursively calling the setter.

#3 Defining a getter but forgetting to return the calculated result.

Why it happens: A property getter must return the value it computes; without return, callers receive None.

Incorrect Approach
script.py
python
Defining a getter but forgetting to return the calculated result.
Correct Solution
script.py
python
Use an explicit return statement whenever the property is supposed to produce a value.

Key takeaway: Use an explicit return statement whenever the property is supposed to produce a value.

#4 Assuming @property automatically validates assigned values.

Why it happens: @property creates attribute-like access to a method but does not automatically validate values; validation must be implemented in a setter or another method.

Incorrect Approach
script.py
python
Assuming @property automatically validates assigned values.
Correct Solution
script.py
python
Validation occurs only when you implement it, usually in a setter or another controlled update method.

Key takeaway: Validation occurs only when you implement it, usually in a setter or another controlled update method.

#5 Adding a setter that accepts every value without checking the class's rules.

Why it happens: A setter that accepts every input can violate class invariants; validate the value according to the object's requirements before storing it.

Incorrect Approach
script.py
python
Adding a setter that accepts every value without checking the class's rules.
Correct Solution
script.py
python
Validate the assigned value before updating the object's backing attribute.

Key takeaway: Validate the assigned value before updating the object's backing attribute.

#6 Assuming a property without a setter makes the entire object immutable.

Why it happens: A property without a setter prevents assignment through that property, but other attributes on the object can still be mutable.

Incorrect Approach
script.py
python
Assuming a property without a setter makes the entire object immutable.
Correct Solution
script.py
python
A read-only property blocks normal assignment through that property. Other attributes and methods can still change the object.

Key takeaway: A read-only property blocks normal assignment through that property. Other attributes and methods can still change the object.

#7 Using a property for a slow or side-effect-heavy operation.

Why it happens: Property access looks like ordinary attribute access, so expensive I/O or surprising side effects can make code difficult to reason about.

Incorrect Approach
script.py
python
Using a property for a slow or side-effect-heavy operation.
Correct Solution
script.py
python
Keep property access predictable and lightweight. Use a method when an operation has substantial work or noticeable side effects.

Key takeaway: Keep property access predictable and lightweight. Use a method when an operation has substantial work or noticeable side effects.

#8 Using properties for every simple attribute.

Why it happens: Properties are useful when validation or computed behavior is needed, but ordinary public attributes are simpler when no extra behavior is required.

Incorrect Approach
script.py
python
Using properties for every simple attribute.
Correct Solution
script.py
python
Prefer ordinary public attributes when direct access is clear and no additional behavior is required.

Key takeaway: Prefer ordinary public attributes when direct access is clear and no additional behavior is required.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is encapsulation in Python?
Answer:
Encapsulation is the practice of keeping related state and behavior together and exposing a clear interface for interacting with an object. Python supports this through class design, naming conventions, properties, and methods. Its conventions help communicate intended access, but they do not make ordinary attributes completely private.
Q2:What is the difference between public and non-public attributes in Python?
Answer:
Public attributes, such as name, are intended for ordinary external use. Names beginning with one underscore, such as _name, conventionally indicate implementation details that callers should generally avoid depending on. Python still allows direct access to a single-underscore attribute.
Q3:What is name mangling?
Answer:
When a class defines a name with two leading underscores and without two trailing underscores, Python transforms the name using the class name. This reduces accidental name clashes, particularly in inheritance. It is not a security mechanism or strict privacy.
Q4:What is a property, and why would you use one?
Answer:
A property allows a method to be accessed through attribute-style syntax. It is useful for calculated values, read-only interfaces, validation, or changing an implementation without changing how callers access an attribute.
Q5:How do you define a property setter?
Answer:
First define a property using @property, then define a setter for that same property using @property_name.setter. The setter receives the assigned value, validates it when necessary, and updates a backing attribute such as _value.
Q6:What causes infinite recursion in a property setter?
Answer:
If a setter assigns to the same property, such as self.value = new_value inside the value setter, it invokes itself again. Repeating that assignment causes recursive calls until Python raises RecursionError. Store the value in a separate backing attribute instead.
Q7:What is the difference between a read-only property and an immutable object?
Answer:
A read-only property has no setter, so normal assignment through that property is not allowed. The object itself may still have other writable attributes or methods that change state. Read-only access to one property does not make the entire object immutable.
Q8:When should you use a property instead of a method?
Answer:
Use a property for lightweight access to information that naturally behaves like an attribute, including calculated or validated values. Use a method when the operation requires explicit arguments, performs a substantial action, or has side effects that should be visible in the call.
Q9:How can a property help maintain valid object state?
Answer:
A setter can validate a new value before storing it and raise an exception when the value violates the class's rules. The class should also ensure its constructor and other state-changing methods preserve those same rules.
Q10:Do properties prevent callers from changing an underscore-prefixed backing attribute?
Answer:
No. A backing attribute such as _balance is still accessible in Python. The underscore communicates that it is an implementation detail. Properties provide a controlled public interface for normal use, not protection against deliberate access to the backing attribute.

Key takeaways

  • Encapsulation groups state and behavior behind a clear interface.
  • Public attributes are intended for normal use; a leading underscore signals non-public implementation details.
  • Double-leading-underscore names undergo name mangling, which helps avoid accidental name clashes but does not provide security.
  • @property exposes a getter through attribute-style access.
  • A setter defined with @property_name.setter can validate assignments before storing values.
  • Use a separate backing attribute such as _value inside a property setter to avoid recursion.
  • A property without a setter is read-only through that property, but it does not make the whole object immutable.
  • Use methods for meaningful state changes and properties for natural attribute-style access.
  • Choose the simplest interface that maintains the class's required invariants.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: