它不是,是因为在寻找类的Python描述符只检查时达属性,而不是在实例工作的原因;问题的方法是:
它可以覆盖以落实情况以及类descriptor protocol上你的类这些方法:
# do not use in production, example code only, needs more checks
class ClassAllowingInstanceDescriptors(object):
def __delattr__(self, name):
res = self.__dict__.get(name)
for method in ('__get__', '__set__', '__delete__'):
if hasattr(res, method):
# we have a descriptor, use it
res = res.__delete__(name)
break
else:
res = object.__delattr__(self, name)
return res
def __getattribute__(self, *args):
res = object.__getattribute__(self, *args)
for method in ('__get__', '__set__', '__delete__'):
if hasattr(res, method):
# we have a descriptor, call it
res = res.__get__(self, self.__class__)
return res
def __setattr__(self, name, val):
# check if object already exists
res = self.__dict__.get(name)
for method in ('__get__', '__set__', '__delete__'):
if hasattr(res, method):
# we have a descriptor, use it
res = res.__set__(self, val)
break
else:
res = object.__setattr__(self, name, val)
return res
@property
def world(self):
return 'hello!'
当上述类被用作如下:
huh = ClassAllowingInstanceDescriptors()
print(huh.world)
huh.uni = 'BIG'
print(huh.uni)
huh.huh = property(lambda *a: 'really?')
print(huh.huh)
print('*' * 50)
try:
del huh.world
except Exception, e:
print(e)
print(huh.world)
print('*' * 50)
try:
del huh.huh
except Exception, e:
print(e)
print(huh.huh)
的结果是:
你好!
BIG
真的吗?
不能删除属性
你好!
不能删除属性
真的吗?
为什么不使用MyClass的不同子类与overriden描述符? – KurzedMetal
编辑添加更多示例。我猜每个实例描述符不能完成。我已经使用__getattr__解决了它。尽管如此,仍然不明白底层语言约束。 –
描述符只在班级工作,对不起。 –