Content · Programming · Python

Python Encapsulation Through Properties and Validation

Keep an object in a valid state by validating changes through properties.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Keep an object in a valid state by validating changes through properties.

What You Will Learn


A property provides attribute-like access while letting a class validate assignments. Store the actual value in an internal attribute and reject invalid updates with a meaningful exception. This is preferable to scattering repeated validation checks across calling code. Properties are not a substitute for broader business rules or authentication.

A real application should also decide whether decimal currency types are needed.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

class Product:
    def __init__(self, price):
        self.price = price

    @property
    def price(self):
        return self._price

    @price.setter
    def price(self, value):
        if value < 0:
            raise ValueError("Price cannot be negative")
        self._price = value

item = Product(12)
item.price = 15
print(item.price)

How the Example Works


  • The class Product groups data and behavior; its methods run when called on an instance.
  • The variable item holds the result of Product(12). Later lines use that value or inspect how it changes.
  • The variable item.price holds the result of 15. Later lines use that value or inspect how it changes.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

For the chosen input, the expression item.price prints 15. Compare that result with the rule above before you change the argument.

Expected output from the example:

15

When You Would Use This


Decide which input types are valid, what output should be produced, and which cases should fail clearly. A small self-contained demonstration is a good starting point before adding file access, network calls, or application state.

Practice: Modify the Code


Try setting a negative price, catch ValueError and confirm the previous value remains.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Assigning to self.price inside the price setter and causing recursion.
  • Checking a new value in __init__ but allowing invalid assignments later.

Key Takeaways


  • Keep an object in a valid state by validating changes through properties.
  • A property provides attribute-like access while letting a class validate assignments.
  • A real application should also decide whether decimal currency types are needed.
Share this resourceSend this page to someone who may find it useful.