python - 从另一个类修改一个类的功能
问题描述
在server.sync的 pymodbus 库中,使用了SocketServer.BaseRequestHandler,定义如下:
class ModbusBaseRequestHandler(socketserver.BaseRequestHandler):
""" Implements the modbus server protocol
This uses the socketserver.BaseRequestHandler to implement
the client handler.
"""
running = False
framer = None
def setup(self):
""" Callback for when a client connects
"""
_logger.debug("Client Connected [%s:%s]" % self.client_address)
self.running = True
self.framer = self.server.framer(self.server.decoder, client=None)
self.server.threads.append(self)
def finish(self):
""" Callback for when a client disconnects
"""
_logger.debug("Client Disconnected [%s:%s]" % self.client_address)
self.server.threads.remove(self)
def execute(self, request):
""" The callback to call with the resulting message
:param request: The decoded request message
"""
try:
context = self.server.context[request.unit_id]
response = request.execute(context)
except NoSuchSlaveException as ex:
_logger.debug("requested slave does not exist: %s" % request.unit_id )
if self.server.ignore_missing_slaves:
return # the client will simply timeout waiting for a response
response = request.doException(merror.GatewayNoResponse)
except Exception as ex:
_logger.debug("Datastore unable to fulfill request: %s; %s", ex, traceback.format_exc() )
response = request.doException(merror.SlaveFailure)
response.transaction_id = request.transaction_id
response.unit_id = request.unit_id
self.send(response)
# ----------------------------------------------------------------------- #
# Base class implementations
# ----------------------------------------------------------------------- #
def handle(self):
""" Callback when we receive any data
"""
raise NotImplementedException("Method not implemented by derived class")
def send(self, message):
""" Send a request (string) to the network
:param message: The unencoded modbus response
"""
raise NotImplementedException("方法未由派生类实现")
当客户端连接到服务器时调用 setup(),当客户端断开连接时调用 finish()。我想在另一个使用库(pymodbus)的文件的另一个类中操作这些方法(setup()和finish()),并添加一些代码来设置和完成函数。我不打算修改库,因为它可能会在特定情况下导致奇怪的行为。
---已编辑----为了澄清,我希望 ModbusBaseRequestHandler 类中的设置函数像以前一样工作并且保持不变,但是添加其他东西,但是这个修改应该在我的代码中而不是在库中完成。
解决方案
它可以通过拦截器完成
from functools import wraps
def iterceptor(func):
print('this is executed at function definition time (def my_func)')
@wraps(func)
def wrapper(*args, **kwargs):
print('this is executed before function call')
result = func(*args, **kwargs)
print('this is executed after function call')
return result
return wrapper
@iterceptor
def my_func(n):
print('this is my_func')
print('n =', n)
my_func(4)
更多解释可以在这里找到
推荐阅读
- python - 如何删除python中pandas数据框列中每个元素的最后2个字符?
- c++ - 是否有与 C++ 中的地图等效的 z3 容器?
- javascript - 如何在使用 Node JS 和 Mocha 测试的不同文件中正确使用 afterEach
- tensorflow - Keras 模型预测有 nan 损失并预测 nan 值
- python - 如何从 SQL Server MS 执行外部 python 脚本文件(托管在远程桌面上)
- node.js - listObjectsV2 使用 nodejs 列出嵌套“文件夹”中的所有对象
- github - 你能从终端触发一个 github webhook
- r - 如何用包latex2exp在xlab中做概率符号?
- bash - 自动重新启动已终止的作业 [bash]
- python - 未捕获的类型错误:无法读取未定义的属性(读取“开始”)