3 回答
TA贡献1890条经验 获得超9个赞
一种可能的方法是使用property(属性是用 Python 中的描述符实现的,因此您可以编写自己的描述符以获得更强大和灵活的属性访问控制):
class BaseWorkFlow:
def __init__(self, response=None):
self._response = response
@property
def response(self):
return self._response
@response.setter
def response(self, value):
self._response = value
# logging after setting
print(f'self._response = {self._response}')
def func1(self):
self.response = 10
def func2(self):
self.response = 20
def func3(self):
self.response = 20
bwf = BaseWorkFlow()
bwf.func1()
bwf.response = 101
输出:
self._response = 10
self._response = 101
TA贡献1775条经验 获得超8个赞
您可以通过分离更新响应值和日志记录的代码来实现它。
import logging
logger = logging.getLogger(__name__)
class BaseWorkFlow:
def __init__(self, response=None):
self.response = response
def func1(self):
self.update_response(10)
def func2(self):
self.update_response(20)
def func3(self):
self.update_response(20)
def update_response(response_value):
self.response = response_value
logger.info(selfl.response.data)
TA贡献1866条经验 获得超5个赞
使用__setattr__捕捉不断变化的类属性的值。
import logging
logger = logging.getLogger(__name__)
class BaseWorkFlow:
def __init__(self, response=None):
self.response = response
def __setattr__(self, name, value):
if name == 'response':
logger.info('{} is set to {}'.format(name, value))
def func1(self):
self.response = 10
def func2(self):
self.response = 20
def func3(self):
self.response = 30
添加回答
举报