2011-04-24 72 views
1

是否有可能使属性断言当它(用于调试的目的)改变了吗?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 
+0

你能举一个你的意思吗? – 2011-04-24 09:11:06

+0

@jcomeau_ictx:done – 2011-04-24 09:17:59

回答

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 
+0

'c.my_property = 123'不会断言这种方式。 – 2011-04-24 09:21:57

+0

我的不好,我忘了使用**属性()**内建 – x10 2011-04-24 09:24:07

+0

如果你想以'c.my_property = 123'的身份访问它,你需要将它设置为'property' – ianalis 2011-04-24 09:25:01

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 
+0

不应该'_bar'是一个成员变量,而不是一个类变量? – 2011-04-24 09:28:40

+0

是的,你是对的。 :) – ianalis 2011-04-24 09:45:05

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