Python утверждать на множестве свойств

1

Можно ли утверждать свойство при его изменении (с целью отладки)?

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: сделано
Теги:

3 ответа

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
    Мое плохое, я забыл , используя свойство () встроенная
Показать ещё 3 комментария
2

Добавьте логическое значение, чтобы проверить, установлено ли значение раньше:

EDIT: но вы хотите свойство, поэтому вам нужно создать его:

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
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 не _bar быть переменной-членом, а не переменной класса?
  • 0
    Да вы правы. :)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню