问题的要点:如果继承多个类,我怎么能保证如果一个类被继承,子对象也使用一个恭维抽象基类(abc)。
我一直在搞乱pythons继承,试图看看我能做什么很酷的事情,我想出了这个模式,这很有趣。
我一直在尝试使用它来更轻松地实现和测试与我的缓存交互的对象。我有三个模块:
- ICachable.py
- 可缓存的.py
- 一些类.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
可缓存的.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
一些类.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 的依赖?