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?')
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?')
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')
It works! But is this plausible or is there a way to use a decorator in class definition B?
source
share