Reputation: 2019
I decided to give learning python a go today, going in the traditional "try random things until something works" way.
I started reading about classes, and then properties, and I tried to create some on my own. Most examples, and even examples from questions on this site, define properties like this:
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
# etc. taken from the python tutorial
When I start typing "@pro" in my text editor and hit tab, it completes to this:
# ... Class stuff ...
@def foo():
doc = "The foo property."
def fget(self):
return self._foo
def fset(self, value):
self._foo = value
foo = property(**foo())
Do these do the same thing, if they do, which one should I use (i.e. which is considered better practice)?
Upvotes: 2
Views: 1637
Reputation: 36718
As has been mentioned, @def foo():
is invalid syntax and should be def foo():
. With that one caveat, the two code samples you posted do pretty much the same thing. The @
operator takes a function-that-works-on-functions and applies it to the next defined function. In other words:
@property
def the_answer():
return 42
is exactly the same as:
def the_answer():
return 42
the_answer = property(the_answer)
But the @property
way of writing this is easier to write, read, and understand, which is why it's considered better practice.
Upvotes: 3