I am trying to decorate an instance method which prints the full name with another method that simply adds a designation and I've managed to figure out this much.
class DecoratorTest:
def __init__(self):
self._first_name = ['CHARLES', 'WILIAM', 'ENID']
self._last_name = ['DICKENS', 'SHAKESPEARE', 'BLYTON']
self._full_name = None
class designation(object):
def __init__(self, decorated):
self._decorated = decorated
def __call__(self, *args, **kwargs):
self._full_name = "MR" + self._decorated()
return self._full_name
@designation()
def full_name(self):
if not self._full_name:
self._full_name = random.choices(self._first_name) + random.choices(self._last_name)
return self._full_name
a = DecoratorTest()
print(a.full_name())
With some reading, I figured out that the decorator @designation cannot be an instance method since the first argument would be self and not the function that needs to be decorated so any call to it would immediately fail which is why I've specified the decorator designation
as a class hoping that the redefined descriptor __call__()
would help here.
What I'm unable to figure out is how to proceed further. I keep running into various errors and no amount of trial and error is getting me the solution.
EDIT
After some work, I managed to get this to work albeit after ditching the class decorator, the problem now however is that it is an instance method which brings up the issue pointed out in the blog link I mentioned in my comment i.e. in this link https://medium.com/@vadimpushtaev/decorator-inside-python-class-1e74d23107f6
How can I solve this ?
import random
class DecoratorTest:
def __init__(self):
self._first_name = ['CHARLES', 'WILIAM', 'ENID']
self._last_name = ['DICKENS', 'SHAKESPEARE', 'BLYTON']
self._full_name = None
def designation(func):
def wrapper(self):
full_name = "MR" + func(self)
return full_name
return wrapper
@designation
def full_name(self):
if not self._full_name:
self._full_name = str(random.choices(self._first_name)) + str(random.choices(self._last_name))
return self._full_name
a = DecoratorTest()
print(a.full_name())