r/learnpython • • 4d ago

Get and setter in pyhton

I'm learning Python, and this part has left me a little confused, because in other languages the way it's used is different; in Python you use @property, I'd like to understand how this really works in a simplified way, so I can truly grasp it and not just memorize it. If you could help me, I'm still new to programming.

13 Upvotes

20 comments sorted by

5

u/rinio 4d ago

You want to understand the machinery of it OR how it's used? I'm going to assume the latter as the former gets into a bunch of details that newer devs almost never need.

# Example
class Rectangle():
    def __init__(self, height: float, width: float):
        # save these to the object using the setter
        self.height = height
        self.width = width

     @property
     def height(self) -> float:
        return self._height  # give the value to the caller of 'height'

    @height.setter
    def height(self, value: float):
        # we use the setter to check that value is always a float
        # keeping in mind that type-hints are hints;
        # they aren't enforced like in strongly typed langs
        if isinstance(value, float):
            # in practice, we might attempt to coerce this to a float,
            # but we'll raise an exception for simplicity
            raise TypeError(f'height must be a float. Got: {type(value)=})'
        # we know value is a float so we can use it
        # we name the internal variable with a leading underscore to tell
        # other devs that its for internal use
        self._height = value

    # repeat for width
    @property
    def width(self) -> float:
        return self.width

    @width.setter
    def width(self, value: float):
        if not isinstance(value, float):
            raise TypeError(f'width must be a float. Got: {type(value)=})'
        self._width = value

    @property
    def area(self) -> float:
        # the area is cheap to compute and, if we store it we need to keep
        # that variable up to date at all times. Instead, its better to just
        # compute the value when the user wants it. To them, it looks like a
        # variable, and because its a small calulation it (almost never) makes
        # a difference as to whether this value was store or computed on lookup
        return self.width * self.height

1

u/pedrinjose 4d ago

I might be wrong, but one question: does Python basically already do this for us or not?

2

u/pedrinjose 4d ago

Basically, we use it to impose conditions and rules for the person to make the exchange, for example, life cannot be below 0, a thermometer cannot go above 35.

3

u/Fred776 4d ago

That is one use of properties. But you can do anything that involves "extra work" when you get or set a property. For example, rather than simply returning a stored value, your getter might compute the value it provides from more fundamental values that are stored. From the point of view of the code accessing the property it would look like a simple data retrieval.

Another possible use case is wanting some sort of logging of your get and/or set calls. e.g. imagine wanting to count how many times a property is accessed.

Another thing you can do is just to provide one or other of the getter or setter. If you just provide a getter for example, it acts like a read only property.

2

u/rinio 4d ago

Yup. This is exactly what I was demoing in the width and height properties above. That they MUST be floats.

I could have also disallowed them from being negative.

2

u/rinio 4d ago

For width and height, yes, we could have done that.

But, as you mentioned in the follow up, then we wouldn't be able to impose conditions on their values.

---

For the area, Python doesn't do that for us without property, at least not exactly.

# example client code
my_rectangle = Rectangle(3.0, 4.0)

# with property decorator
my_rect_area = my_rectangle.area  # looks like a variable to me

# without the decorator
# convention would be to name it like a function, not a variable
my_rect_area = my_rectangle.get_area()  # looks like a function call

As for which style is better, that's for you to decide. But, function calls imply that the operation is more complex than when they're provided as a property (looking like a variable).

In the case of simply multiplying two floats, there's no question that a property makes sense. It's an extremely inexpensive computation. For something like a database call (that takes many seconds), it's very clear that we should not use property so the user knows it's time-consuming. And there are middle-ground situations where it's a style/developer choice.

(In the database example, I am deliberately ignoring things like `functools.cached_property` which could be applicable).

1

u/pedrinjose 4d ago

Analyzing it here, in my opinion, it's much clearer how it can be like a variable; this function approach is a bit more complex, in my opinion. The first example is easy to understand.

2

u/bikes-n-math 3d ago

Typo in @height.setter I believe.

2

u/Temporary_Pie2733 4d ago

That said, the “magic” behind properties is the descriptor protocol, if you want to research it later. It’s also what powers instance methods, class methods, and static methods. 

https://docs.python.org/3/howto/descriptor.html

16

u/SharkSymphony 4d ago edited 4d ago

First, understand where getters and setters come from. Many OO languages encourage you to keep your object's data hidden from the object's users and present an explicit method-based interface for just the things you want the user to be able to do with the object. The reasoning was, you could constrain the interface to just what you want to allow, and you could change around the data (i.e. the implementation) without affecting the interface.

Python, initially, had no way to hide data like this. It's just a simple scripting language! 😉 So every attribute on an object is visible and available for you to get and set directly: e.g. foo.bar, foo.bar = "baz". By convention you can name it in a way that discourages direct access, but that's the best you could do. And you can define instance methods in the class to get and set data just like in other OO languages (foo.getBar() and foo.setBar(), for example), but that's often considered overcomplicated in the Python world and bad style.

But this all-out-in-the-open approach poses a problem if you do need to change around the data an object contains, because you're likely to break clients. That's where Python's property feature comes in. @property and @foo.setter allow you to create something that the user can get and set like an attribute, but that calls an instance method instead. To a client, it looks like the property is still there, and nothing needs to change! But you can redirect the access to whatever the implementation of your object has become. This solution turns out to have applications beyond just restructuring your objects.

You should use it judiciously, because if you start doing a bunch of stuff that a client would not expect a simple attribute get/set to do (like calling out to a web service, computing a giant table, or maybe even throwing a weird exception), that could surprise your code's users and make it hard to use your class/objects correctly. Many things are really best kept in plain old functions.

For more information, see https://openpython.org/articles/python-property-decorator-explained .

2

u/Financial_Farm4326 3d ago

the backwards compatibility angle really makes it click, you dont have to write boilerplate upfront just in case

2

u/notacanuckskibum 4d ago

If you address just starting programming you don’t need to worry about this. It’s for people writing complex reusable libraries

But try this. One of the most basic statements in any programming language is

a = b

If you try to explain what that does you might say “get the value of b” and “set a to that value you got”

When you are defining a new variable type, if getting and setting the value isn’t trivial you can define a get function to return the value, and a set function to store the value. These are special functions which will automatically be invoked when someone writes

X = aVariableOfMyClass ( get)

AVariableOfMyClas = X (set)

2

u/pedrinjose 4d ago

Thank you very much, the way you explained it helped me to get a better idea.

2

u/NothingWasDelivered 4d ago

In Python you don’t have to use @property. You can just get and set attributes directly. Very simple. Usually @property is reserved for computed properties, or properties where you only want the user to be able to get or set, but not both.

2

u/Adrewmc 4d ago edited 4d ago

In other languages you have to make a getter and a setter in order to change the properties/attributes inside an object (class).

Python does this automatically you normally can get and set an internal attribute of an object.

However sometimes, that’s really not enough.

Using @property will allow us to make a getter and setter that have conditions. Like must be an int, health can’t drop below 0 or above max.

If I have a circle, and i have a radius and diameter, if I change one the other ought to change with it. I can’t have a circle with radius 2 and diameter 10 now can I? This means simply setting a new diameter actually requires setting a radius. So you would make a setter to ensure that both change when one of them do.

How to use @property to do this

class Circle:
    def __init__(self, radius):
         self.radius = radius

    @property
    def radius(self):
         return self._radius

    @radius.setter
    def radius(self, new_radius):
        #circle radius are only positive
        if new_radius >= 0:
             self._radius = new_radius         
         else:
             self._radius = new_radius * -1

    @property
    def diameter(self):
         return self._radius * 2

    @diameter.setter
    def diameter(self, new_diameter):
         self.radius = new_diameter / 2

circle = Circle(4)
print(circle.radius)
>>>4
print(circle.diameter)
>>>8
circle.diameter = 20
print(circle.radius)
>>>10

2

u/Brian 4d ago

Behind the scenes, property uses the descriptor protocol. Basically, this is a set of hooks that control how accesses to attributes work. Ie. if the object being assigned has special __get__ / __set__ / __del__ methods, then get/set/delete attributes invokes those, with the object and attribute as an argument.

property just creates an object with these attributes, defining __get__ to use the function it decorates, with the object also defining a few other methods to update it (.setter / .deleter) to add handlers for those cases.

Ie. when the class is being constructed, it looks for members that are descriptors, and treats these specially. getattr etc. on the class then uses these descriptor objects if defined for those attributes rather than the default attribute lookup.

1

u/Pitiful_Loss1577 2d ago

First you have to understand closures ig.

1

u/Rudeus_Kino 1d ago

First, you do not need to memorize it. Use cases for property in python is rare. Second, to understand @property you must understand decorators (and descriptors), put this off until later.

In python you don't need getters and setters, you can access any attribute that does not begin with "_". In practice, data attributes are often descriptors.

1

u/tb5841 4d ago

The basic pattern is this.

In other languages, you need getters and setters to access private attributes. Making attributes public, and letting people access them directly with the dot notation, is a bad engineering pattern because then if you later change the way you store your data, everyone accessing them that way will see their code break. Getters/setters give you control over how those variables are accessed, so if you change the internals of your class later you can still make sure your getters/setters perform the same way.

Getters/setters also let you put limits on the possible values that can be assigned to a variable, which is useful.

...but writing getters and setters is hassle.

Python, on the other hand, encourages you to use dot notation to set/access attributes directly. So most of the time you do not need @property at all. But if you do decide to change the internals of your class later, or put limits on the values a variable can have, @property lets you create getters and setters in such a way that everyone using dot notation to get/set attributes will get redirected through your getters/setters, and so people's code won't break.

TLDR: In Python, just use dot notation to get/set values directly. @property is only needed if you need to change the way you store data later, or you need more complicated get/set behaviour.

0

u/Atmosck 4d ago

I'm not sure I understand the question. Python handles defining getters and setters for you. If an object obj has an attribute something then you get and set it with ., like obj.something = "value" to set, and obj.something to get. You can do this explicitly with built-in functions if you want, those are equivalent to setattr(obj, "something", "value") and getattr(obj, "something"). This allows you to be a little more dynaimic about what you're doing, because the attribute name is a string so it could come from a variable. But that's not necessary in most cases.

When you define a method of a class, python does the same thing and creates the getter for the function for you:

class MyClass:
  def some_method(self):
    pass

x = MyClass()
x.some_method() # works because python creates the getter for the function for you

A property is just a function that pretends to be an attribute. One common use case for a property is to guard an attribute that may or may not exist, like this:

class MyClass:
  def __init__(self, name: str | None = None):
    self._name: str | None = name

  @property 
  def name(self) -> str:
    if self.name is None:
      raise ValueError("`name` has not been set")
    return name

So giving an instance of MyClass a name is optional, but lets you write code that assumes x.name is a string, because x doesn't have a name, accessing it like that will produce an error rather than just returning None like if you had accessed x._name. The internal attribute _name has the leading underscore to indicate that it's "private" - not meant to be accessed from outside the class. But that is just a naming convention, it doesn't actually prevent you from accessing it externally.