2

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)?

Ron
  • 1,989
  • 2
  • 17
  • 33
  • Possible duplicate of [this question](http://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters) – msvalkon Apr 25 '13 at 08:11
  • 1
    `@def foo()` is invalid syntax – jamylak Apr 25 '13 at 08:11
  • 3
    Your editor is using outdated autocompletions (pre -`@decorator`s) - it's completing `property` to `def foo() ...`, leaving the literal `@`. – Eric Apr 25 '13 at 08:12
  • @msvalkon Not at all, IMO. – glglgl Apr 25 '13 at 08:48
  • 1
    @def appears to be broken behavior in sublime texts (And maybe others?) autocomplete. That said its a shame. It'd be a rather pleasing syntactical construction if it worked. – Shayne Aug 04 '14 at 04:50

1 Answers1

3

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.

rmunn
  • 34,942
  • 10
  • 74
  • 105
  • A function-that-works-on-functions is usually called a "decorator", by the way. If you want to learn more about them, that's the term you should Google, not "function-that-works-on-functions". :-) – rmunn Apr 25 '13 at 08:53
  • By the way, if you want to learn more about decorators, this answer to a question from 2009 is a fantastic tutorial on the subject: http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python/1594484#1594484 – rmunn Apr 25 '13 at 08:56