简体   繁体   中英

Match All Methods between two Python Sub-Modules

I have a customized module with following hierarchy:

module
  __init__.py
  kernel1
    __init__.py
    alg1.py
    alg2.py
  kernel2
    __init__.py
    alg1.py
    alg2.py

Here, kernel1 and kernel2 should implement exactly the same series of algorithms but using different bottom libraries.

I am wondering if there is a way that I can ensure every method defined in kernel1 has a counterpart in kernel2 , and vice versa. For example, if there is a function f_kernel1 defined in kernel1 (either alg1.py or alg2.py ), it should have a function f_kernel2 defined in kernel2 (either alg1.py or alg2.py )

One of the many possible solutions is to define kernel1 and kernel2 as classes that contain functions (or wrappers to your implemented functions), and inherit from a common abstract base class.

This way the base class defines an empty implementation for the common functions, and each of the derived classes need to implement them (and this is enforced in several python IDEs)

Abstract classes can be defined with abc module.

for example:

from abc import ABC, abstractmethod

class KernelBase(ABC):
    @abstractmethod
    def func1(self):
        pass

class Kernel1(KernelBase):
    def func1(self):
        ...

class Kernel1(KernelBase):
    def func2(self):
        ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM