Fundamentals 8 min read

Unlock Python’s @property: Turn Methods into Seamless Attributes

This article explains how Python’s @property decorator transforms class methods into attribute-like accessors, covering basic usage, setter/getter patterns, error handling, and practical examples such as score validation and temperature conversion, helping developers write cleaner, more encapsulated code.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Unlock Python’s @property: Turn Methods into Seamless Attributes

1. Advantages of Using @property

Converting class methods to class attributes allows direct retrieval or assignment of values, providing encapsulation.

Case Study

class Exam(object):
    def __init__(self, score):
        self._score = score

    def get_score(self):
        return self._score

    def set_score(self, val):
        if val < 0:
            self._score = 0
        elif val > 100:
            self._score = 100
        else:
            self._score = val

    e = Exam(60)
    print(e.get_score())
    e.set_score(70)
    print(e.get_score())

Code analysis: The Exam class hides the internal _score attribute and provides get_score and set_score methods to enforce validation, demonstrating encapsulation.

Using @property

Python’s @property decorator lets a method be accessed like an attribute.

class Exam(object):
    def __init__(self, score):
        self._score = score

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, val):
        if val < 0:
            self._score = 0
        elif val > 100:
            self._score = 100
        else:
            self._score = val

    e = Exam(60)
    print(e.score)
    e.score = 90
    print(e.score)
    e.score = 200
    print(e.score)

Note: Adding @property makes score behave like an attribute; a corresponding @score.setter allows assignment. Without a setter, the property becomes read‑only.

class Exam(object):
    def __init__(self, score):
        self._score = score

    @property
    def score(self):
        return self._score

    e = Exam(60)
    print(e.score)
    # e.score = 200  # AttributeError: can't set attribute

2. The Power of @property

Python uses property to manage attribute access and validation.

class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    def get_temperature(self):
        print("Getting value")
        return self._temperature

    def set_temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273°C is impossible")
        print("Setting value")
        self._temperature = value

    temperature = property(get_temperature, set_temperature)

Creating an instance triggers __init__, which assigns self.temperature = temperature, automatically invoking the setter.

2. Role of the attribute

Accessing c.temperature calls get_temperature() automatically.

c = Celsius()
print(c.temperature)
print(c.to_fahrenheit())

Note: The temperature value is stored in a private variable _temperature; the temperature property provides a controlled interface.

3. Deep Dive into property

In Python, property() is a built‑in function that creates a property object.

property(fget=None, fset=None, fdel=None, doc=None)

Parameters: fget retrieves the value, fset sets it, fdel deletes it, and doc is an optional docstring.

Example of creating a property object:

temperature = property(get_temperature, set_temperature)

Equivalent explicit construction:

# Create empty property
temperature = property()
# Set getter
temperature = temperature.getter(get_temperature)
# Set setter
temperature = temperature.setter(set_temperature)

Both approaches are functionally identical.

2. Example

class Celsius:
    def __init__(self, temperature=0):
        self._temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    @property
    def temperature(self):
        print("Getting value")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273°C is impossible")
        print("Setting value")
        self._temperature = value

c = Celsius()
c.temperature = 37
print(c.temperature)

Note: Using @property with matching getter and setter is the recommended, concise way to create managed attributes in Python.

4. Summary

This article introduced Python’s @property decorator, showing how it converts methods into attributes through examples, demonstrating its power, error handling, and the role of properties in encapsulation.

Try implementing it yourself; hands‑on practice deepens understanding.

Simple code, hope it helps your learning.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonDecoratorPropertygettersetter
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.