Created
April 10, 2020 12:57
-
-
Save StephenFordham/dc43293bc108cc503699caf4ded60277 to your computer and use it in GitHub Desktop.
Class_decorators_with_and_without_default_arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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