我遵循了“python cookbook”关于“实现数据模型或类型系统”主题的建议,代码如下:
class Descriptor(object):
def __init__(self, name=None, **opts):
self.name = name
for key, value in opts.items():
setattr(self, key, value)
def __set__(self, instance, value):
instance.__dict__[self.name] = value
class Unsigned(Descriptor):
def __init__(self, name=None, **opts):
super(Unsigned, self).__init__(name, **opts)
def __set__(self, instance, value):
print 'child set value: ', value
if value < 0:
raise ValueError("Expected value > 0")
super(Unsigned, self).__set__(instance, value)
但是,__set__
部分的代码似乎不适用于子类。尝试时的原因:
test = Unsigned("Judy") #this works fine, the __init__ part
test = -9 # there's no error raised, but the __set__ function in the child class is supposed to raise such error \
因为这个类型检查类不允许否定
我不知道问题出在哪里..初始化工作正常.. 有什么建议吗?
非常感谢!
最佳答案
描述符应该存在于类声明中,如下所示:
class Foo(object): # don't need (object) in 3.x
bar = Unsigned('bar')
来自docs :
In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol.
然后您打算实例化该类并将描述符用作属性:
foo = Foo()
foo.bar = -7 # this should throw an exception
如果您尝试直接分配给描述符,描述符将不会执行任何操作:
Foo.bar = -7 # just replaces the descriptor with -7
...如果您不首先将它们放入一个类中:
baz = Unsigned('baz')
baz = -7 # just set the variable to -7
关于python 子类 __set__ 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30623369/