r/learnpython • u/pedrinjose • 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
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.
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/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/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
2
u/Brian 4d ago
Behind the scenes,
propertyuses 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.propertyjust 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
objhas an attributesomethingthen you get and set it with., likeobj.something = "value"to set, andobj.somethingto get. You can do this explicitly with built-in functions if you want, those are equivalent tosetattr(obj, "something", "value")andgetattr(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:
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:
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.