Created
May 10, 2020 16:45
-
-
Save StephenFordham/549b6796a98951b891b60eece58deceb to your computer and use it in GitHub Desktop.
method_decorators
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
# 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