Python在属性集上断言

时间:2011-04-24 09:08:33

标签: python

是否可以在更改属性时进行声明(为了调试)?

class MyClass(object):
    def set_my_property(self, value):
        self.my_property = value
        # TODO: mark my_property so that if it gets set again, an assert
        # is triggered

c = MyClass()
c.set_my_property(4)

# any of these lines would cause an assertion
c.set_my_property(8)
c.my_property = 123

3 个答案:

答案 0 :(得分:2)

修改: 这是你在找什么?

class MyClass(object):
    def __init__(self):
        self.trigger = False
        self._my_property = 0

    def set_my_property(self, value):
        if self.trigger:
            raise Exception("WHOOPS!")
        self._my_property = value
        # TODO: mark my_property so that if it gets set again, an assert
        # is triggered
        self.trigger = True

    def get_my_property(self):
        return self._my_property

    my_property = property(get_my_property, set_my_property, None)

c = MyClass()
c.set_my_property(4)

# any of these lines would cause an assertion
c.set_my_property(8)
c.my_property = 123

答案 1 :(得分:2)

添加一个布尔值以检查是否在之前设置了值:

编辑:但是你想要一个属性,所以你需要创建一个:

class MyClass(object):
    def __init__(self):
        self.my_property_set = False
        self._my_property = None

    def set_my_property(self, value):
        self._my_property = value
        assert not self.my_property_set,"my_property already set"
        self.my_property_set = True

    def get_my_property(self):
        return self._my_property

    my_property = property(get_my_property, set_my_property, None)

c = MyClass()
c.set_my_property(4)

# any of these lines would cause an assertion
c.set_my_property(8)
c.my_property = 123

答案 2 :(得分:0)

class Foo:
    def __init__(self):
        self._bar = None

    @property
    def bar(self): return self._bar

    @bar.setter:
    def bar(self, value):
        assert value != some_constant # your assert condition
        self._bar = value

    @bar.deleter:
    def bar(self, value):
        assert value != some_constant # your assert condition
        self._bar = None