how to use @ in python.. and the @property and the @classmethod

python

Solution

A decorator needs to be a callable object (either a function or an object implementing __call__), where the parameter is the function that has been decorated, and the result is a function that will replace the function that has been decorated, so, to use your example of printing 'sss' instead of printing 'aaa':

>>> def a(f):
...     def replacementfunc():
...         print 'sss'
...     return replacementfunc;
... 
>>> @a
... def b():
...     print 'aaa'
... 
>>> b()
sss

Or, a more elaborate example:

>>> class print_decorator(object):
...     def __init__(self,text):
...        self.text = text;
...     def __call__(self,f):
...        def replacement():
...            print self.text;
...        return replacement;
... 
>>> @print_decorator("Hello world!")
... def b():
...     print 'aaa';
... 
>>> b()
Hello world!

Edit As for your updated question, you need to look at the documentation for @property. It's not clear exactly what you are trying to accomplish, although my guess is that you want:

class a:
    @property
    def b(self):
        return 'sss'

aa=a()
print aa.b # prints 'sss', whereas without @property, prints <function ... >

Problem

this is my code: ``` def a(): print 'sss' @a() def b(): print 'aaa' b() ``` and the Traceback is: ``` sss Traceback (most recent call last): File "D:\zjm_code\a.py", line 8, in <module> @a() TypeError: 'NoneType' object is not callable ``` so how to use the '@' thanks updated ``` class a: @property def b(x): print 'sss' aa=a() print aa.b ``` it print : ``` sss None ``` how to use @property thanks updated2 and the classmethod: ``` class a: @classmethod def b(x): print 'sss' aa=a() print aa.b ``` the it print : ``` <bound method classobj.b of <class __main__.a at 0x00B2DC00>> ```

Original source