2011-04-24 4 views
1

변경할 때 속성을 어설트 할 수 있습니까 (디버깅 목적으로)?속성 집합에 파이썬 assert

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

무슨 뜻인지 예를 들려 주시겠습니까? –

+0

@jcomeau_ictx : done –

답변

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'은이 방법을 주장하지 않습니다. –

+0

나쁘다. ** property() ** builtin을 사용하는 것을 잊어 버렸다. – x10

+0

'c.my_property = 123'으로 액세스하려면 'property'로 지정해야한다. – ianalis

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'가 클래스 변수가 아닌 멤버 변수가되어서는 안됩니까? –

+0

네, 맞습니다. :) – ianalis

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