python子类__set__不工作

时间:2015-06-03 14:43:33

标签: python class subclass

我遵循" 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 \ 

因为此类型检查类

不允许否定

我无法告诉问题可能在哪里......初始化工作正常.. 有什么建议吗?

非常感谢!

1 个答案:

答案 0 :(得分:1)

描述符应该存在于类声明中,如下所示:

class Foo(object):  # don't need (object) in 3.x
    bar = Unsigned('bar')

来自docs

  

通常,描述符是具有“绑定行为”的对象属性,其属性访问已被描述符协议中的方法覆盖。

然后,您要实例化该类并将该描述符用作属性:

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