0

问题的要点:如果继承多个类,我怎么能保证如果一个类被继承,子对象也使用一个恭维抽象基类(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 的依赖?

4

1 回答 1

0

如果您明确不希望继承,则可以将类注册为 ABC 的虚拟子类。

@ICacheable.register
class Cacheable:
    ...

这意味着每个子类也Cacheable被自动视为子类ICacheablesuper如果您有一个有效的实现,该实现会因遍历非功能性抽象基类(例如调用)而减慢,这将非常有用。

但是,ABC 不仅仅是接口,可以从它们继承。事实上,ABC 的部分好处是它强制子类实现所有抽象方法。一个中间帮助类,例如Cacheable,在它从未实例化时不实现所有方法是可以的。但是,任何实例化的非虚拟子类都必须是具体的。

>>> class FailClass(Cacheable, ICacheable):
...    ...
...
>>> FailClass()
TypeError: Can't instantiate abstract class FailClass with abstract methods CacheItemIns, Load, _deserializeCacheItem, _deserializeNonCacheItem

请注意,如果您

  • 总是子类为class AnyClass(Cacheable, ICacheable):
  • 从不实例化Cacheable

这在功能上等同于Cacheable继承自ICacheable. 方法解析顺序(即继承菱形)是相同的。

>>> AnyClass.__mro__
(__main__. AnyClass, __main__.Cacheable, __main__.ICacheable, abc.ABC, object)
于 2018-08-09T16:10:14.517 回答