Python's built-decorator (decorator) explained

@python built decorator to explain the meaning

Read a blog about python decorators, benefited greatly:
https://www.cnblogs.com/cicaday/p/python-decorator.html

Python is a function of the decorators Essentially, it allows the other functions do not need to add additional features under the premise of any code changes, decorator return value is a function object. It is often used has cut demand scenarios, such as: insert log, performance testing, transaction processing, caching, check the permissions and other scenes. Decoration is a great design to solve these problems, with the decorators, we can draw a large number of identical code is not related to the function itself and continue to function reuse.

The built decorator @property @staticmethod @classmethod document check, the current interpreter python 69 contains built-in method (Built-in Function), property, staticmethod, classmethod which is the three.

1.@property

class property(fget=None, fset=None, fdel=None, doc=None)

Returns a property attribute, fget / fset / fdel are get, set, del function, doc to create docstring attribute

Common usage is:

class Line(object):
    def __init__(self, start=Point(0, 0), end=Point(0, 0)):
        self._start = start
        self._end = end
        
    @property
    def start(self):
        return self._start
        
    @start.setter
    def start(self, start):
        self._start = start
  • Why do I need to use getter function?
    If not used, the output of the memory location where the property rather than the property values. In short, @ property to create the equivalent of a getter function.
  • Why use the first instance of @ start.setter with @property, you do not need .getter, behind?
    property is a built-in method (built-in function), @Property after use, which process is equivalent to the property is instantiated, the object is returned (callable object) a call, start both instances of property default to the getter function . Ie start = property(getx, setx, delx). Object property contains three methods: getter, setter, deleter. Follow @ start.setter is a call to setter function.

2.@staticmethod

The function converts a static function that returns a staticmethod objects,

Can be called either on the class (such as Cf ()) or on an instance (such as C (). F ()). May be used based call (Cf ()), may be instantiated call (C () .f ())

class C:
@staticmethod
def f(arg1, arg2, ...):
	......

https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner

3.@classmethod

The class function into a function

class C:
@classmethod
def f(cls, arg1, arg2, …): …

Guess you like

Origin blog.csdn.net/houhuipeng/article/details/90751432