Python property() built-in function

From the Python 3 documentation

Return a property attribute.

Introduction

The property() function is used to create property attributes. A property attribute is a special kind of attribute that has getter, setter, and delete methods. This allows you to add logic to getting, setting, or deleting an attribute’s value.

It’s more common to use the @property decorator, which is a more convenient way to use property().

Example

Here’s an example of using property() to create a read-only attribute:

class Person:
    def __init__(self, name):
        self._name = name

    def get_name(self):
        print("Getting name")
        return self._name

    # Create a property
    name = property(get_name)

p = Person("John")
print(p.name)  # This calls get_name()
# Output:
# Getting name
# John

# p.name = "Jane" # This would raise an AttributeError because there is no setter

And here is the more common way to do it with the @property decorator:

class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        print("Getting name")
        return self._name

p = Person("John")
print(p.name)
# Output:
# Getting name
# John

Subscribe to pythoncheatsheet.org

Join 16,702+ Python developers in a two times a month and bullshit free publication , full of interesting, relevant links.