python-decorators

What is the difference between @staticmethod and @classmethod?

不想你离开。 提交于 2019-11-26 03:12:34
问题 What is the difference between a function decorated with @staticmethod and one decorated with @classmethod? 回答1: Maybe a bit of example code will help: Notice the difference in the call signatures of foo , class_foo and static_foo : class A(object): def foo(self, x): print "executing foo(%s, %s)" % (self, x) @classmethod def class_foo(cls, x): print "executing class_foo(%s, %s)" % (cls, x) @staticmethod def static_foo(x): print "executing static_foo(%s)" % x a = A() Below is the usual way an

How does the @property decorator work?

为君一笑 提交于 2019-11-26 01:18:09
问题 I would like to understand how the built-in function property works. What confuses me is that property can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator. This example is from the documentation: class C(object): def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, \"I\'m the \'x\' property.\") property \'s

How to make a chain of function decorators?

谁都会走 提交于 2019-11-25 23:56:03
问题 How can I make two decorators in Python that would do the following? @makebold @makeitalic def say(): return \"Hello\" ...which should return: \"<b><i>Hello</i></b>\" I\'m not trying to make HTML this way in a real application - just trying to understand how decorators and decorator chaining works. 回答1: Check out the documentation to see how decorators work. Here is what you asked for: from functools import wraps def makebold(fn): @wraps(fn) def wrapped(*args, **kwargs): return "<b>" + fn(

What does the “at” (@) symbol do in Python?

时光总嘲笑我的痴心妄想 提交于 2019-11-25 22:44:37
问题 I\'m looking at some Python code which used the @ symbol, but I have no idea what it does. I also do not know what to search for as searching Python docs or Google does not return relevant results when the @ symbol is included. 回答1: An @ symbol at the beginning of a line is used for class, function and method decorators . Read more here: PEP 318: Decorators Python Decorators The most common Python decorators you'll run into are: @property @classmethod @staticmethod If you see an @ in the