python child class __set__ 不工作

python child class __set__ not working

我听从了 "python cookbook" 关于主题 "Implementing Data Model or Type System" 的建议,代码如下:

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__ 部分的代码似乎不适用于子class。尝试时的原因:

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

我不知道问题出在哪里..初始化工作正常.. 有什么建议吗?

非常感谢!

描述符应该位于 class 声明中,如下所示:

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.

然后您打算实例化 class 并将描述符用作属性:

foo = Foo()
foo.bar = -7  # this should throw an exception

如果您尝试直接分配给描述符,描述符将不会执行任何操作:

Foo.bar = -7  # just replaces the descriptor with -7

...如果您不首先将它们放入 class:

baz = Unsigned('baz')
baz = -7  # just set the variable to -7