【问题标题】:Adding specific methods to class after determine device version - python确定设备版本后向类添加特定方法 - python
【发布时间】:2020-01-15 21:21:19
【问题描述】:

我设计了我的框架,因此它将在其中包含设备(带有元数据的类)和其中负责连接到设备上的特定接口(使用设备元数据)并执行命令的接口(对象)列表并返回输出。
此接口通常包含处理来自设备的输出的方法。
例如:执行一些 show 命令,使用输出创建数据帧并返回此数据帧。

现在我发现此输出可能与设备上安装的版本不同。
因此,我想创建包含此特定方法(非通用)的模块,并根据设备版本动态添加它们(猴子补丁)。
例如:如果设备版本是1.8.20-6 我将搜索 1.8.20.py 模块并添加它。

现在我找到了如何装饰这些函数@some_decorater,以便在运行时将它们添加到接口类中。
如果我使用以下代码通过完整路径添加这些模块:

import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)

python解释器是否会自动搜索所有修饰函数并将它们添加到接口类中?
或者有其他方法可以解决这个问题吗?也许是一些处理它的python包。

我的另一个问题是为什么 pycharm IDE 在我尝试导入它们时无法识别名为 x.y.z.py 或 x_y_z.py 的模块 (import framework.Versions.x_y_z)?

顺便说一句,我知道这不是一个典型的代码问题,而是更多的“如何”问题。

【问题讨论】:

    标签: python class interface decorator


    【解决方案1】:

    为每个设备构建一个特定的接口可能是一个更好的主意,并使用工厂来选择和返回正确的对象:

    使用设备作为参数调用get_device_adapter,将返回正确的DeviceAdapter 对象。

    伪代码:

    class AbstractDeviceAdapter(ABC):
        def __init__(self, ...):
            initiatlize the common attributes
            ...
        def common_method_1(self):
            pass
        def common_method_2(self):
            do 2
        @abstractmethod
        def device_specific_method_0(self):
            pass
        @abstractmethod
        def device_specific_method_1(self):
            pass
    
    
    class Device01Adapter(AbstractAdapterInterface):
        def device_specific_method_0(self):
            do specific stuff for device 01
        def device_specific_method_1(self):
            do specific stuff for device 01
    
    
    class Device02Adapter(AbstractAdapterInterface):
        def device_specific_method_0(self):
            do specific stuff for device 02
        def device_specific_method_1(self):
            do specific stuff for device 02
    
    
    def get_device_adapter(device, ...):
        """
        returns the Adapter appropriate for the given device
        """
        if '01' in device.__version__:
            return Device01Adapter(...)
        if '02' in device.__version__:
            return Device02Adapter(...)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-27
      相关资源
      最近更新 更多