python decorator Decorator Implementation Python Built-in Decorators

Maybe you know Design Pattern, then you don’t feel unfamiliar with decorator pattern. decorator in python is just similar to the thought.

decorator pattern is such a structure that you can extend the function of a class and don’t need to inherit from it.

You also need to know what’s closure:
‘The criteria that must be met to create closure in Python are summarized in the following points.

  • We must have a nested function (function inside a function).
  • The nested function must refer to a value defined in the enclosing function.
  • The enclosing function must return the nested function.’
    ‘Closures can avoid the use of global values and provides some form of data hiding. It can also provide an object oriented solution to the problem.’

‘Functions and methods are called callable as they can be called.
In fact, any object which implements the special method call() is termed callable. So, in the most basic sense, a decorator is a callable that returns a callable.’

Decorator Implementation

Python Built-in Decorators

@property

With Pythonic way, you almost never need to implement explicit setter and getter methods. If you need special behavior when an attribute is set, you can migrate to the @property decorator and its corresponding setter attribute. The build-in @property decorator is :
property(fget=None, fset=None, fdel=None, doc=None)
For example,

def ():
doc = "The property."
def fget(self):
return self._value
def fset(self, value):
self._value = value
def fdel(self):
del self._value
return locals()
foo = property(**(foo))

class A(object):
def __init__(self):
self._v = 0
self.cc = 1


def v(self):
return self._v


@v.setter
def v(self, v):
self._v = v
self.cc = self._v / 10

The big problem with the @property built-in is reuse.

@classmethod & @staticmethod

Python only supports a single constructor per class, which is the init method. Use @classmethod to define alternative constructors for your classes, and also whether you call the method from the instance or the class, it passes the class as first argument..
Use class method polymorphism to provide generic ways to build and connect
concrete subclasses.

Ref: