gpt4 book ai didi

Python 断言属性集

转载 作者:太空宇宙 更新时间:2023-11-04 11:00:41 25 4
gpt4 key购买 nike

是否可以在属性更改时断言它(出于调试目的)?

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

最佳答案

编辑:这是你要找的吗?

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

关于Python 断言属性集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5769660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com