2011-04-24 69 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