Try this: Python Property

The sample code is:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        print("getter of x called")
        return self._x

    @x.setter
    def x(self, value):
        print("setter of x called")
        self._x = value

    @x.deleter
    def x(self):
        print("deleter of x called")
        del self._x


c = C()
c.x = 'foo'  # setter called
foo = c.x    # getter called
del c.x      # deleter called
Answer from Grissiom on Stack Overflow
๐ŸŒ
Real Python
realpython.com โ€บ python-getter-setter
Getters and Setters: Manage Attributes in Python โ€“ Real Python
January 20, 2025 - In this enhanced version of Employee, you turn .name and .birth_date into properties using the @property decorator. Now each attribute has a getter and a setter method named after the attribute itself. Note that the setter of .name turns the input name into uppercase letters.
Top answer
1 of 9
1159

Try this: Python Property

The sample code is:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        print("getter of x called")
        return self._x

    @x.setter
    def x(self, value):
        print("setter of x called")
        self._x = value

    @x.deleter
    def x(self):
        print("deleter of x called")
        del self._x


c = C()
c.x = 'foo'  # setter called
foo = c.x    # getter called
del c.x      # deleter called
2 of 9
628

What's the pythonic way to use getters and setters?

The "Pythonic" way is not to use "getters" and "setters", but to use plain attributes, like the question demonstrates, and del for deleting (but the names are changed to protect the innocent... builtins):

value = 'something'

obj.attribute = value  
value = obj.attribute
del obj.attribute

If later, you want to modify the setting and getting, you can do so without having to alter user code, by using the property decorator:

class Obj:
    """property demo"""
    #
    @property            # first decorate the getter method
    def attribute(self): # This getter method name is *the* name
        return self._attribute
    #
    @attribute.setter    # the property decorates with `.setter` now
    def attribute(self, value):   # name, e.g. "attribute", is the same
        self._attribute = value   # the "value" name isn't special
    #
    @attribute.deleter     # decorate with `.deleter`
    def attribute(self):   # again, the method name is the same
        del self._attribute

(Each decorator usage copies and updates the prior property object, so note that you should use the same name for each set, get, and delete function/method.)

After defining the above, the original setting, getting, and deleting code is the same:

obj = Obj()
obj.attribute = value  
the_value = obj.attribute
del obj.attribute

You should avoid this:

def set_property(property,value):  
def get_property(property):  

Firstly, the above doesn't work, because you don't provide an argument for the instance that the property would be set to (usually self), which would be:

class Obj:

    def set_property(self, property, value): # don't do this
        ...
    def get_property(self, property):        # don't do this either
        ...

Secondly, this duplicates the purpose of two special methods, __setattr__ and __getattr__.

Thirdly, we also have the setattr and getattr builtin functions.

setattr(object, 'property_name', value)
getattr(object, 'property_name', default_value)  # default is optional

The @property decorator is for creating getters and setters.

For example, we could modify the setting behavior to place restrictions the value being set:

class Protective(object):

    @property
    def protected_value(self):
        return self._protected_value

    @protected_value.setter
    def protected_value(self, value):
        if acceptable(value): # e.g. type or range check
            self._protected_value = value

In general, we want to avoid using property and just use direct attributes.

This is what is expected by users of Python. Following the rule of least-surprise, you should try to give your users what they expect unless you have a very compelling reason to the contrary.

Demonstration

For example, say we needed our object's protected attribute to be an integer between 0 and 100 inclusive, and prevent its deletion, with appropriate messages to inform the user of its proper usage:

class Protective(object):
    """protected property demo"""
    #
    def __init__(self, start_protected_value=0):
        self.protected_value = start_protected_value
    # 
    @property
    def protected_value(self):
        return self._protected_value
    #
    @protected_value.setter
    def protected_value(self, value):
        if value != int(value):
            raise TypeError("protected_value must be an integer")
        if 0 <= value <= 100:
            self._protected_value = int(value)
        else:
            raise ValueError("protected_value must be " +
                             "between 0 and 100 inclusive")
    #
    @protected_value.deleter
    def protected_value(self):
        raise AttributeError("do not delete, protected_value can be set to 0")

(Note that __init__ refers to self.protected_value but the property methods refer to self._protected_value. This is so that __init__ uses the property through the public API, ensuring it is "protected".)

And usage:

>>> p1 = Protective(3)
>>> p1.protected_value
3
>>> p1 = Protective(5.0)
>>> p1.protected_value
5
>>> p2 = Protective(-5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
  File "<stdin>", line 15, in protected_value
ValueError: protectected_value must be between 0 and 100 inclusive
>>> p1.protected_value = 7.3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 17, in protected_value
TypeError: protected_value must be an integer
>>> p1.protected_value = 101
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 15, in protected_value
ValueError: protectected_value must be between 0 and 100 inclusive
>>> del p1.protected_value
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 18, in protected_value
AttributeError: do not delete, protected_value can be set to 0

Do the names matter?

Yes they do. .setter and .deleter make copies of the original property. This allows subclasses to properly modify behavior without altering the behavior in the parent.

class Obj:
    """property demo"""
    #
    @property
    def get_only(self):
        return self._attribute
    #
    @get_only.setter
    def get_or_set(self, value):
        self._attribute = value
    #
    @get_or_set.deleter
    def get_set_or_delete(self):
        del self._attribute

Now for this to work, you have to use the respective names:

obj = Obj()
# obj.get_only = 'value' # would error
obj.get_or_set = 'value'  
obj.get_set_or_delete = 'new value'
the_value = obj.get_only
del obj.get_set_or_delete
# del obj.get_or_set # would error

I'm not sure where this would be useful, but the use-case is if you want a get, set, and/or delete-only property. Probably best to stick to semantically same property having the same name.

Conclusion

Start with simple attributes.

If you later need functionality around the setting, getting, and deleting, you can add it with the property decorator.

Avoid functions named set_... and get_... - that's what properties are for.

Discussions

property decorator VS setters and getters , which is better and why ?
Getters and setters are not usually needed in Python. Just access properties directly using the . notation. If you really need to do something more complex than just setting/returning something, then you can use the property decorator. In most other languages accessing properties directly using the . notation is problematic because if you change the internal workings of your class later, everyone else using the . notation will find their code breaks. Hence the use of private methods, and getters/setters. In Python you can use the . notation everywhere, and if you change the internal workings of your class later you can use the property decorator so everyone's code will still work. More on reddit.com
๐ŸŒ r/learnpython
25
12
January 26, 2025
What is the purpose of a property's @getter decorator?
Can anyone explain the purpose of the @property.getter decorator? class Foo(object): # Create a property (with a getter) @property def answer(self): return 41 # Change the getter @answer.getter def answer(self): return 42 I suppose that itโ€™s sort of cool that this works, but what is the use ... More on discuss.python.org
๐ŸŒ discuss.python.org
0
0
February 6, 2025
Is it *always* better to use setters and getters? Or is that a personal preference/making code more or less pythonic thing?

The "always use setters/getters" thing comes from the wider OOP world in general, and the Java world in particular. It's good advice in the Java world because if you use a property to give access to a value inside an object and later that property must be computed, meaning you have to change the property to a getter function, then all user code must change, which is bad.

Python has mechanisms to allow an object's computed property to be accessed as if it was a simple property, so the above problem doesn't occur.

More on reddit.com
๐ŸŒ r/learnpython
48
85
April 22, 2017
Why does Python @property decorator take 4 arguments if we only pass it 1?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/learnprogramming
5
1
June 27, 2023
๐ŸŒ
Medium
aignishant.medium.com โ€บ understanding-python-property-decorators-getters-setters-57d6b535e5d2
Understanding Python Property Decorators: Getters, Setters | by Nishant Gupta | Medium
February 23, 2025 - The property decorator in Python is a powerful feature that allows you to define โ€œgetterโ€, โ€œsetterโ€ methods for class attributes without explicitly calling them as methods.
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ property
Python @property Decorator (With Examples)
In this tutorial, you will learn about Python @property decorator; a pythonic way to use getters and setters in object-oriented programming.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ getter-and-setter-in-python
Getter and Setter in Python - GeeksforGeeks
July 11, 2025 - In this approach, the @property decorator is used for the getter and the @<property_name>.setter decorator is used for the setter.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-property-decorator
The @property Decorator in Python: Its Use Cases, Advantages, and Syntax
December 19, 2019 - A getter - to access the value of the attribute. A setter - to set the value of the attribute. A deleter - to delete the instance attribute. Price is now "Protected" Please note that the price attribute is now considered "protected" because ...
Find elsewhere
๐ŸŒ
Tutorjoes
tutorjoes.in โ€บ python_programming_tutorial โ€บ property_decorator_getter_setter_in_python
Property Decorator Getter Setter in Python
# Property Decorators Getter Setter class student: def __init__(self, total): self._total = total def average(self): return self._total / 5.0 @property def total(self): return self._total @total.setter def total(self, t): if t < 0 or t > 500: print("Invalid Total and can't Change") else: self._total = t o = student(450) print("Total : ", o.total) print("Average : ", o.average()) o.total = 550 print("Total : ", o.total) print("Average : ", o.average()) To download raw file Click Here
๐ŸŒ
DEV Community
dev.to โ€บ the1kimk โ€บ function-decorators-in-python-understanding-property-getter-and-setter-methods-3a8e
Function Decorators in Python: Understanding @property, Getter, and Setter Methods - DEV Community
September 22, 2024 - In this example, the getter (get_price()) and setter (set_price()) provide a way to access and modify the _price attribute while enforcing certain rules (like ensuring the price is not negative). The @property Decorator Python offers a more elegant way to manage access to private attributes using the @property decorator.
๐ŸŒ
Analytics Vidhya
analyticsvidhya.com โ€บ home โ€บ getter and setter in python
Getter and Setter in Python - Analytics Vidhya
February 17, 2024 - The above example defines a `Person` class with a private attribute _name. We use the `@property` decorator to define a getter method `name` that returns the value of _name.
๐ŸŒ
Llego
llego.dev โ€บ home โ€บ blog โ€บ python getter and setter methods: a comprehensive guide
Python Getter and Setter Methods: A Comprehensive Guide - llego.dev
July 17, 2023 - Here are some best practices to follow when implementing getter and setter methods in Python: Give descriptive names like get_name() and set_name() following conventions. Use @property decorator for getter methods and @<attribute>.setter for setters.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Python OOP Tutorial 6: Property Decorators - Getters, Setters, and Deleters - YouTube
In this Python Object-Oriented Tutorial, we will be learning about the property decorator. The property decorator allows us to define Class methods that we c...
Published ย  August 19, 2016
๐ŸŒ
Python Course
python-course.eu โ€บ oop โ€บ properties-vs-getters-and-setters.php
3. Properties vs. Getters and Setters | OOP | python-course.eu
December 2, 2023 - ... class P: def __init__(self, x): self.x = x @property def x(self): return self.__x @x.setter def x(self, x): if x < 0: self.__x = 0 elif x > 1000: self.__x = 1000 else: self.__x = x ยท A method which is used for getting a value is decorated with "@property", i.e.
๐ŸŒ
Packetswitch
packetswitch.co.uk โ€บ python-getters-setters-and-property-decorator
Python Getters, Setters and @property Decorator
November 1, 2025 - Now let's look at a way to start our class with dot notation attributes while allowing us to introduce getters and setters later without breaking existing code. class Person: def __init__(self, name, age): self.name = name self.age = age ยท So, we can start our code like this (shown above), and users will naturally use p1.name to access attributes. Later, if we need to add validation or logic, we can easily introduce the @property decorator (shown below) without breaking any existing code.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
What is the purpose of a property's @getter decorator? - Python Help - Discussions on Python.org
February 6, 2025 - Can anyone explain the purpose of the @property.getter decorator? class Foo(object): # Create a property (with a getter) @property def answer(self): return 41 # Change the getter @answer.geโ€ฆ
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-39888.html
Curious about decorator syntax
April 30, 2023 - I'm curious as to the rationale behind the choice of decorator syntax for getters and setters. Take, for example: @property def prop(self): return self._prop @prop.setter def prop(self, value): if not isinstan...
๐ŸŒ
Studytonight
studytonight.com โ€บ python โ€บ property-in-python
Python @property decorator and property() function | Studytonight
@property is a built-in decorator in python language which is used to make functions like getters and setters in a class behave as class properties.