Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python @property design

A design question about python @property, I've encountered this two options:

Option-1:

class ThisIsMyClass(object):

    @property
    def ClassAttr(self):
        ...

    @ClassAttr.setter
    def ClassAttr(self, value):
        ...

Option-2:

class ThisIsMyClass(object):

    def set_ClassAttr(self, value):
        ...

    def get_ClassAttr(self):
        ...

    myProperty = property(get_ClassAttr, set_ClassAttr)

Question:

I would like to know if there is any difference by using those 2 options?

If so how does it influencing my code?

like image 378
Kobi K Avatar asked Nov 06 '13 15:11

Kobi K


2 Answers

They are exactly equivalent. Refer to the documentation to see for yourself:

http://docs.python.org/2/library/functions.html#property

The @ option seems to me more readable (code in two contiguous lines), easier to refactor (grep for all @ decorators and proceed), and easier to remember. It was meant as syntactic sugar for the second method, and I would advice sticking to it.

If for any reason you need to support a Python version which does not support the @ functionality (2.6), then you would need to stick to the property (second option) method.

On an unrelated note: I would suggest that you keep member attributes named using lowercase word separated by underscore. This is, of course, a matter of preference, but is aligned with Python style recommendation (PEP8). There are important exceptions to this advice but, if you can help it, leave capitalized letters for class names.

like image 154
Escualo Avatar answered Nov 09 '22 09:11

Escualo


The only differences are syntax and exposing the other names using the second option. You could, for example, use obj.set_ClassAttr(value) with the latter.

The first option used to be unavailable, as properties predate decorators.

like image 40
Roger Pate Avatar answered Nov 09 '22 08:11

Roger Pate