Properties Defined With Property() And @property
Solution 1:
They are equivalent, but the first one is preferred as many people find it more readable (while also not cluttering the code and the namespace). The problem with the second method is that you are defining two methods that you will never use, and they remain in the class.
One would use the second method only if they have to support a very old Python version, which does not support decorators syntactic sugar. Function and method decorators were added in Python 2.4 (while class decorators only in version 2.6), so that is in almost all cases a problem of the past.
Solution 2:
In the old days (pre python 2.4), the decorator syntax (i.e. @property
) didn't exist yet, so the only way to create decorated functions was to use your second method
time = property(fget=get_time, fset=set_time)
The PEP that lead to decorators gives many reasons for the motivation behind the newer syntax, but perhaps the most important is this one.
The current method of applying a transformation to a function or method places the actual transformation after the function body. For large functions this separates a key component of the function's behavior from the definition of the rest of the function's external interface.
It's much clearer with the newer @
syntax that a property exists by simply skimming through the code and looking at the method/property definitions.
Unfortunately, when they first added the new @property
decorator, it only worked for decorating a getter. If you had a setter or a deleter function, you still had to use the old syntax.
Luckily, in Python 2.6, they added the getter
, setter
, and deleter
attributes to properties so you could use the new syntax for all of them.
These days, there's really no reason to ever use the old syntax for decorating functions and classes.
Post a Comment for "Properties Defined With Property() And @property"