Reputation: 217
I understand how properties and classes work in Python with the clearest example of using properties I can think of is when setting a temperature to not let it go below absolute zero. I am now wondering it is a good idea to use a property if the method is actually going to be some transformation.
Grabbing this example of properties from Wikipedia:
class Pen(object):
def __init__(self):
self._color = 0 # "private" variable
@property
def color(self):
return self._color
@color.setter
def color(self, color):
self._color = color
Let's say that color was important to class of Pen and makes sense to be there, but the actual value setter looks something more like this:
@color.setter
def color(self, rgb_hex):
self._color = hex_handler.get_color(rgb_hex)
I like that from the object perspective, you just have the color, but the implementation is a little obfuscated to someone unless they dig into it. So is that a good way to use properties or should it be something more like:
def set_color_from_rgb_hex(self, rgb_hex):
self._color = hex_handler.get_color(rgb_hex)
Where it's clearer how color is actually derived.
Upvotes: 2
Views: 150
Reputation: 29071
The whole idea is exactly the opposite: you don't what the user of the class to know how color is implemented. That's what the whole point of classes and encapsulation is.
The user just makes an assignment
my_object.color = 'some_hex_value'
and let's the class handle that.
The idea of properties is that you should use your object member variables as public, and define getters and setters afterwards, only if something changes. Contrast that with eg. java, where you define getters and setters that do nothing in most cases, just to be covered in case something changes.
If the color is that important to you class, maybe you should create a Color
class, and the Pen
class should only accept instances of that. However, that's impossible to tell unless you give further information.
Upvotes: 1