以下代码:
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/