Python Tip of the Day: Use @property for Clean Attribute Access

Use @property for Clean Attribute Access

Author: Jeremy Morgan
Published: November 13, 2024


Coding with AI

I wrote a book! Check out A Quick Guide to Coding with AI.
Become a super programmer!
Learn how to use Generative AI coding tools as a force multiplier for your career.


Turn class methods into read-only attributes. Cleaner code, same functionality!

# Class with @property
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @property
    def area(self):
        return self.width * self.height

rect = Rectangle(3, 4)
print(rect.area)  # Output: 12

“Python Tip of the Day: Use @property for Clean Attribute Access”


The Python Tip of the Day is a daily series published in the month of November. The tips are designed to help you become a better Python programmer. I post tips like this and more every single day on X. Let’s connect!


Coding with AI

I wrote a book! Check out A Quick Guide to Coding with AI.
Become a super programmer!
Learn how to use Generative AI coding tools as a force multiplier for your career.