Decorators and Descriptors gel together beautifully.
Create an Accessor Descriptor
class Accessor(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, obj, type):
if obj is None:
return self
return self.fget(obj)
## Use as Decorator
python
class Greet():
msg = "meow"
@Accessor
def yo(self):
return "Yo!"
Now greetThem.yo returns "Yo!" without calling ().
The Magic: When Python finds a descriptor in the class dictionary, it executes it instead of returning it!
#python
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.