Hemanth's Scribes

python

Descriptor Decorator in Python

Author Photo

Hemanth HM

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