Question

At some point I encountered a piece of code like this, written in python:

class Foo(object):
    @Mystery
    def bar():
       return 5+3
print Foo().bar

Which printed 8. However I cannot remember what the decorator was called. Am I imagining things, or does this exist? And if it does exist what is it called?

Was it helpful?

Solution

You are looking for @property.

You may want to read up on how the @property decorator works.

In short, and as you noted, you can use this to provide dynamically calculated attributes on an object. This is very useful in cases where you may have had code that accessed that as an attribute and you don't necessary want to change this to a function call.

However this by default is read-only. To permit the setting of value to that once more, you can create a setter decorator. Here is an example on how you might use it in the real world which also show you how you can make use of this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top