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
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
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is encapsulation in Python?
Q2:What is the difference between public and non-public attributes in Python?
Q3:What is name mangling?
Q4:What is a property, and why would you use one?
Q5:How do you define a property setter?
Q6:What causes infinite recursion in a property setter?
Q7:What is the difference between a read-only property and an immutable object?
Q8:When should you use a property instead of a method?
Q9:How can a property help maintain valid object state?
Q10:Do properties prevent callers from changing an underscore-prefixed 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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: