Skip to content

Instantly share code, notes, and snippets.

@StephenFordham
Created May 10, 2020 16:45
Show Gist options
  • Save StephenFordham/549b6796a98951b891b60eece58deceb to your computer and use it in GitHub Desktop.
Save StephenFordham/549b6796a98951b891b60eece58deceb to your computer and use it in GitHub Desktop.
method_decorators
# Class Decorators: Using Decorators with methods defined in a Class
def integer_check(method):
def inner(ref):
if not isinstance(ref._val1, int) or not isinstance(ref._val2, int):
raise TypeError('val1 and val2 must be integers')
else:
return method(ref)
return inner
class NumericalOps(object):
def __init__(self, val1, val2):
self._val1 = val1
self._val2 = val2
@integer_check
def multiply_together(self):
return self._val1 * self._val2
def power(self, exponent):
return self.multiply_together() ** exponent
# x = NumericalOps(2, 'my_string')
# print(x.multiply_together())
y = NumericalOps(1, 2)
print(y.multiply_together())
print(y.power(3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment