Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StephenFordham/dc43293bc108cc503699caf4ded60277 to your computer and use it in GitHub Desktop.
Save StephenFordham/dc43293bc108cc503699caf4ded60277 to your computer and use it in GitHub Desktop.
Class_decorators_with_and_without_default_arguments
# Full example version with accompanying doc string
class Power(object):
def __init__(self, arg):
self._arg = arg
def __call__(self, *param_arg):
"""If there are decorator arguments, __call__() is only called once
as part of the decoration process. You can only give it a single argument,
which is the function object
If there are no decorator arguments, the function
to be decorated is passed to the constructor.
"""
if len(param_arg) == 1:
def wrapper(a, b):
retval = param_arg[0](a, b)
return retval ** self._arg
return wrapper
else:
expo = 2
retval = self._arg(param_arg[0], param_arg[1])
return retval ** expo
# @Power(3)
# def multiply_together(a, b):
# return a * b
@Power
def multiply_together(a, b):
return a * b
print(multiply_together(2, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment