How to use @ in python .. and @property and @classmethod

this is my code:

def a(): print 'sss' @a() def b(): print 'aaa' b() 

and Traceback:

 sss Traceback (most recent call last): File "D:\zjm_code\a.py", line 8, in <module> @a() TypeError: 'NoneType' object is not callable 

therefore how to use '@'

thanks

updated

 class a: @property def b(x): print 'sss' aa=a() print aa.b 

he prints:

 sss None 

how to use @property

thanks

updated2

and classmethod:

 class a: @classmethod def b(x): print 'sss' aa=a() print aa.b 

he prints:

 <bound method classobj.b of <class __main__.a at 0x00B2DC00>> 
+4
source share
2 answers

The decorator must be a callable object (either a function or an object that implements __call__), where the parameter is a decorated function, and the result is a function that replaces the function that was decorated, therefore, to use your print example 'sss' instead of printing' aaa ':

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

Or a more complex 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 is not clear what exactly you are trying to execute, although I assume that you want:

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

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

The @a() means " a is callable, returning some other callable that can be called with the function as a single argument and will return the callable." If you are not familiar with the term callable , this is simply a generalization of function : it can be a function, a class, or an instance of a class that has a __call__ method.

Your def a returns None , so you are clearly breaking the "decorator contract" that you request with the @a() syntax.

If you just used @a , without () , then a would have to accept the function as its argument and return the called one.

I'm not sure what you are trying to execute, but if it just "prints something in the decorator for the function, then this will work:

 def a(): print 'sss' return lambda f: f 

Now you can use @a() and live happily ever after, as this version respects the β€œdecorator contract,” which I explained in the first paragraph.

+4
source

Source: https://habr.com/ru/post/1308196/


All Articles