2

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.

1
  • 1
    That obfuscation is the whole point. Things seem seamless and neat to the user, so they can write pretty, idiomatic Python without dealing with the fiddly internals. If you're not comfortable with "deceiving" the caller about what's going on that's fine, but you're not breaking any rules here. Commented Jul 11, 2018 at 12:52

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.