That's because descriptors should only be defined as class attributes, not instance attributes:
From docs:
The following methods only apply when an instance of the class
containing the method (a so-called descriptor class) appears in an
owner class (the descriptor must be in either the owner’s class
dictionary or in the class dictionary for one of its parents).
To make descriptor work with instance attributes as well you need to override the __getattribute__
method of BusinessLogic
.(Haven't tested this thoroughly, but works fine for your case):
def __getattribute__(self, attr):
obj = object.__getattribute__(self, attr)
if hasattr(obj, '__get__'):
return obj.__get__(self, type(self))
return obj
In case you've a data descriptor then you need to handle the __setattr__
part as well.
def __setattr__(self, attr, val):
try:
obj = object.__getattribute__(self, attr)
except AttributeError:
# This will be raised if we are setting the attribute for the first time
# i.e inside `__init__` in your case.
object.__setattr__(self, attr, val)
else:
if hasattr(obj, '__set__'):
obj.__set__(self, val)
else:
object.__setattr__(self, attr, val)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…