python - 具有不同接口(interface)的派生类

标签 python inheritance adapter

以下代码:

class Cache:

    def __init__(self):
        self._cache = []

    def store(self, data):
        self._cache.append(data)

    def stats(self):
        print('We are caching {} elements'.format(len(self._cache)))


class LegoCache(Cache):

    def store(self, weight, color):
        Cache.store(self, (weight, color))

存在一个问题,store方法没有实现基类的接口(interface)。

如何改进这段代码?我有以下想法:

  • 不要从 Cache 派生,只是使用它。
  • 将基类中的store方法重命名为store_base

还有其他选择吗?

编辑

基类还必须支持其他用例:

class ZombieCache(Cache):

    def store(self, dead_since, humans_eaten, can_be_saved=False):
        Cache.store(self, dict(
            dead_since=dead_since, 
            humans_eaten=humans_eaten, 
            can_be_saved=can_be_saved))

最佳答案

您可以在基类中使用可变参数列表:

class Cache:

    def __init__(self):
        self._cache = []

    def store(self, *args):
        self._cache.append(args)

    def stats(self):
        print('We are caching {} elements'.format(len(self._cache)))

class LegoCache(Cache):
    pass
    # "overloading" store isn't needed

因此不需要重载此方法或为特殊情况添加不同名称的方法:

cache = Cache()
legoCache = LegoCache()

cache.store(x)
legoCache.store(x, y)

另一种解决方案可能是委托(delegate):

class LegoCache(object):
    def __init__(self):
        self.cache = Cache()

    def store(self, weight, color):
        self.cache.store((weight, color))
        # or just self.cache.store(weight, color) if you use the *args implementation

关于python - 具有不同接口(interface)的派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48556205/

相关文章:

javascript - 了解原型(prototype)继承

python - 使用返回列表的 fixture 参数化 pytest 函数的最佳方法是什么?

python - "Include"工作异常

python - 使用 csv 文件,查找温度平均值

c++ - 带范围检查的自制迭代器

ios - 有没有办法检测 USB 以太网适配器是否以编程方式连接到 iPhone/iPad?

Python:有效地将字节 block 连接成一个大块?

c++ - OOP - 抽象类类型,在基类和派生类中初始化变量

android - BaseAdapter.notifyDataSetChanged 反转元素的顺序

ejb - Weblogic 找不到用于绑定(bind)的 JNDI 名称为 "correct"的资源适配器