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
在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后在程序中使用它。这个过程可能会涉及到很多步骤,比如连接到数据库、查询数据、处理数据等等。
如果你在使用某种编程语言,比如Python,可能会用到一些库来帮助你完成这些任务。这些库就像是工具箱,里面有很多现成的工具,可以让你更轻松地完成工作。
在处理数据时,可能会遇到一些问题,比如数据格式不对、连接失败等。这时候就需要调试,也就是找出问题所在并解决它。调试就像是侦探,帮助你找到程序中的错误。
总之,编程就像是搭建一个复杂的机器,每个部分都需要正确连接,才能让整个机器顺利运转。
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
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
编辑: 这就是你想要的内容吗?
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