How to use a descriptor decorator inside a subclass

I was wondering if a descriptor decoder can be used in a subclass.

class Descriptor():
    def __get__(self, instance_obj, objtype):
        raise Exception('ouch.')
    def decorate(self, f):
        print('decorate', f)
        return f

class A():
    my_attr = Descriptor()

class B():
    @my_attr.decorate
    def foo(self):
        print('hey, whatsup?')

# --> NameError: name 'my_attr' is not defined

This, of course, does not work, since my_attrthere is undefined in the class definition B.

Next I tried:

class B():
    @A.my_attr.decorate
    def foo(self):
        print('hey, whatsup?')

# --> Exception: ouch.

But this approach calls the descriptor method __get__(where the argument instance_objis equal None), and therefore a test exception is thrown. To access the decorator, you can check what the handle itself instance_objwill Nonereturn:

def __get__(self, instance_obj, objtype):
    if instance_obj is None:
        return self
    raise Exception('avoid this')
# --> decorate <function B.foo at 0x1021dd7b8>

It works! But is this plausible or is there a way to use a decorator in class definition B?

+4
source share
1 answer

, __dict__ :

A.__dict__['my_attr'].decorate

, vars():

vars(A)['my_attr'].decorate

@ decorator ( ), :

_A_my_attr = vars(A)['my_attr']
@_A_my_attr.decorate
def foo(self):
    # ...

, , __get__ None, . , property.

+4

Source: https://habr.com/ru/post/1670340/


All Articles