r/PythonLearning • u/pedrinjose • 7d 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.
2
u/realmauer01 7d ago
Becuase their is no privacy there is no need for getter and setter.
Especially not the js style
2
u/Naive_Programmer_232 6d ago edited 6d ago
traditional object-oriented (OOP) implementation of setters/getters
here's a traditional encapsulation example OP using public getter and setter methods. here double underscore prefix self.__name is used; this is called name-mangling. The reason for this is that there is no true private variables in python; this is close though, in the sense, that you cannot directly access the name via the instance by referencing it's form in the class (e.g. person.__name will not work); however, there are still ways to access that variable from the instance directly without method call, hence it's not truly "private".
Anyway, this is traditional example (no runtime type checking, you can implement that as well):
class Person:
# constructor
def __init__(self, name: str, age: int):
# name mangling
self.__name=name
self.__age=age
# public name setter
def set_name(self, name: str) -> None:
self.__name=name
# public age setter
def set_age(self, age: int) -> None:
self.__age=age
# public name getter
def get_name(self) -> str:
return self.__name
# public age getter
def get_age(self) -> int:
return self.__age
# instance
jacksonn_32=Person("Jackson", 22)
# name-mangling effect: instance level access attempt self.__name
jacksonn_32.__name
# AttributeError: 'Person' object has no attribute '__name'
# name-mangling effect: instance level access attempt self.__age
jacksonn_32.__age
# AttributeError: 'Person' object has no attribute '__age'
# why name-mangling is not true private though
print(jacksonn_32._Person__name)
# 'Jackson'
# print name using public getter
print(jacksonn_32.get_name())
# Jackson
# print age using public getter
print(jacksonn_32.get_age())
# 22
# reset name to 'Jacksonn' using public setter
jacksonn_32.set_name("Jacksonn")
# reset age to 32 using public setter
jacksonn_32.set_age(32)
# print name using public getter
print(jacksonn_32.get_name())
# Jacksonn
# print age using public getter
print(jacksonn_32.get_age())
# 32functional programming (FP) sneakpeak: higher order functions / decorators concepts
before moving to @property let's discuss in basic terms the premise of higher order functions. in essence, a regular function (or method if used in a class), accepts input parameters (arguments) that are usually not other Callable objects (constructors / functions / etc). however, there are functions that can accept these arguments in their definition, as well as contain new definitions for functions, as well as return functions. this is a basic synopsis of higher order functions and a notable pillar of functional programming.
in functional programming with python, there is such a higher order function pattern/feature known as a decorator. A decorator in python, syntactically is marked by the @ symbol. so, @property is a decorator named "property" that is built-in to python natively. somewhere behind the scenes there is a definition of what the "property" function is code-wise. i am not going to go further with that definition, because i truly do not know it haha, but I will show you another example of a decorator to illustrate in basic sense what it looks like behind the scenes so you can understand more ex:
def add10_decorator(func):
def add10_wrapper(x,y):
return func(x,y)+10
return add10_wrapper
@add10_decorator
def ten_plus_x_plus_y(x,y):
return x+y
# after definition
ten_plus_x_plus_y(x=10,y=20)
# 40 so in this example, essentially what is happening is by using the @add10_decorator above the ten_plus_x_plus_y function, python is doing this behind the scenes
ten_plus_x_plus_y = add_10_decorator(ten_plus_x_plus_y)on the right side, the old definition of ten_plus_x_plus_y (e.g. return x+y) is being input as an argument to the decorator function; the decorator returns add_10_wrapper which is the inner function definition. so if you check the name associated with the ten_plus_x_plus_y function reference after its definition, noted by # after definition above, you will see the wrapper name:
ten_plus_x_plus_y.__name__
# 'add10_wrapper' on the left side of the assignment, ten_plus_x_plus_y now takes on the extended behavior of the wrapper function; which if you see above inside the wrapper it does func(x,y)+10 where func is a variable representing the old definition of ten_plus_x_plus_y, effectively returning x+y+10.
this is why the behavior in the last part of the given example when ten_plus_x_plus_y(x=10,y=20) is called, it outputs 40 instead of 30; that function's definition has been overwritten with the inner wrapper's definition, so now it takes on that behavior when used.
all of this takes place behind scenes when you use @<decorator name> above the definition of another function or method or even class (e.g. @dataclass from the dataclasses library).
so, hopefully that clarifies things a little bit more with what exactly is going on generally when using a decorator noted by @ symbol above a definition of a callable. now let's look at @property decorator specifically in the next example.
FP+OO setters/getters using @property
how the traditional OOP example differs from @property decorator is that a property is similar, not quite, to an attribute. the decorator is used on a method. but once the instance is created, referencing the property looks the same as you would do with a public attribute, however doing so will invoke the method behind the scenes; so it's not truly an instance related variable as it is a short-hand to call the decorated function; in that sense, a property can be seen as more akin to magic methods (e.g. __getitem__) than normal attributes.
This example uses the same name-mangling case to explore the behavior of properties with getters and setters, you will notice there is no direct call from the instance to utilize these methods ex:
class Person:
# constructor
def __init__(self, name: str, age: int):
# name mangling
self.__name=name
self.__age=age
@property
# public attribute-like name getter method
def name(self) -> str:
return self.__name
@name.setter
# public attribute-like name setter method
def name(self, other_name: str) -> None:
self.__name=other_name
@property
# public attribute-like age getter method
def age(self) -> int:
return self.__age
@age.setter
# public attribute-like age setter method
def age(self, other_age: int) -> None:
self.__age=other_age
# instance
jacksonn_32=Person("Jackson",22)
# name-mangling still in place (not true private 1st example above)
jacksonn_32._Person__name
# 'Jackson'
# notice: no direct method call (e.g. no jacksonn_32.name())
# public property name getter (@property by default is getter)
print(jacksonn_32.name)
# Jackson
# public property age getter
print(jacksonn_32.age)
# 22
# notice: no direct method call (e.g. no jacksonn_32.name("Jacksonn"))
# public property name setter (@name.setter)
jacksonn_32.name="Jacksonn"
# public property age setter (@age.setter)
jacksonn_32.age=32
# public property name getter
print(jacksonn_32.name)
# Jacksonn
# public property age getter
print(jacksonn_32.age)
# 32So that's the basic difference. Hopefully that makes sense.
1
u/AdDiligent1688 7d ago edited 7d ago
@property just makes it so it’s accessible/reassignable the way instance attributes are, unlike a traditional setter or getter method is. You can still do the latter you don’t have to use @property and denote private-like variables via double underscore prefix name mangling ex: self.__var = None, in the constructor, then reference that inside your getter and setter methods, and so on inside the __repr__ magic method if you want to for example.
1
u/recentAd1666 7d ago
We often do not define nor use setters and getters in python. Just use the attribute. If private attribute we define them with underscores __myprivateattribute.
This is mainly a naming convention in python
1
u/Slothemo 7d ago
Private uses a single underscore. Leading double underscore causes name mangling and makes it so attributes are not accessible in child classes.
1
u/atarivcs 7d ago
Generally in python you don't use getters and setters at all, you just assign or access attributes directly.
i.e.
myobject.x = 5
print(myobject.y)
2
u/ninhaomah 7d ago
Pls post the code that you are confused with.
Also the comparison with the other language also.
Pls don't leave people guessing.