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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With