【发布时间】:2018-08-09 00:46:48
【问题描述】:
问题的要点:如果继承多个类,我如何保证如果一个类被继承,子对象也使用一个恭维抽象基类(abc)。
我一直在研究 python 的继承,想看看我能做什么很酷的事情,我想出了这个模式,这很有趣。
我一直在尝试使用它来更轻松地实现和测试与我的缓存交互的对象。我有三个模块:
- ICachable.py
- Cacheable.py
- SomeClass.py
ICacheable.py
import abc
class ICacheable(abc.ABC):
@property
@abc.abstractmethod
def CacheItemIns(self):
return self.__CacheItemIns
@CacheItemIns.setter
@abc.abstractmethod
def CacheItemIns(self, value):
self.__CacheItemIns = value
return
@abc.abstractmethod
def Load(self):
"""docstring"""
return
@abc.abstractmethod
def _deserializeCacheItem(self):
"""docstring"""
return
@abc.abstractmethod
def _deserializeNonCacheItem(self):
"""docstring"""
return
Cacheable.py
class Cacheable:
def _getFromCache(self, itemName, cacheType,
cachePath=None):
"""docstring"""
kwargs = {"itemName" : itemName,
"cacheType" : cacheType,
"cachePath" : cachePath}
lstSearchResult = CacheManager.SearchCache(**kwargs)
if lstSearchResult[0]:
self.CacheItemIns = lstSearchResult[1]
self._deserializeCacheItem()
else:
cacheItem = CacheManager.NewItem(**kwargs)
self.CacheItemIns = cacheItem
self._deserializeNonCacheItem()
return
SomeClass.py
import ICacheable
import Cacheable
class SomeClass(Cacheable, ICacheable):
__valueFromCache1:str = ""
__valueFromCache2:str = ""
__CacheItemIns:dict = {}
@property
def CacheItemIns(self):
return self.__CacheItemIns
@CacheItemIns.setter
def CacheItemIns(self, value):
self.__CacheItemIns = value
return
def __init__(self, itemName, cacheType):
#Call Method from Cacheable
self.__valueFromCache1
self.__valueFromCache2
self.__getItemFromCache(itemName, cacheType)
return
def _deserializeCacheItem(self):
"""docstring"""
self.__valueFromCache1 = self.CacheItemIns["val1"]
self.__valueFromCache2 = self.CacheItemIns["val2"]
return
def _deserializeNonCacheItem(self):
"""docstring"""
self.__valueFromCache1 = #some external function
self.__valueFromCache2 = #some external function
return
所以这个例子有效,但可怕的是没有保证继承Cacheable 的类也继承ICacheable。这似乎是一个设计缺陷,因为Cacheable 本身毫无用处。然而,从我的子类/子类中抽象事物的能力是强大的。有没有办法保证Cacheable对ICacheable的依赖?
【问题讨论】:
-
使
Cacheable成为ICacheable的子类。 -
@mypetlion 让我们进入这个时代,“我怎么知道哪些方法需要在 Cacheable 中被覆盖”。代替 Cacheable 提供辅助实现的助手,它现在实际上是在实现 ICacheable。突然又回到了与 C# 和 Java 相同的问题,但没有它们拥有的一半继承工具(比如声明类范围的能力)。至少我是这么想的。
-
为什么要指定私有方法,例如
_deserializeNonCacheItem,作为接口的一部分?这些不应该是可见的,因此您实际上是在执行一个实现细节。另请注意,__CacheItemIns是受 name mangling 约束的类私有成员 -ICacheable除非声明它,否则永远不能使用它。见docs.python.org/3/tutorial/classes.html#private-variables
标签: python multiple-inheritance abstract-base-class