如何在不同类(继承自同一父类)的实例之间传递相同的变量(iterable)

2024-05-20 00:37:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在不同类的实例之间传递一个变量(iterable)。我的结构与下面的结构相似

每个类都有自己的模块(因此没有全局变量),需要在Python3和Python2中工作

class O:
    pass


class A(O):
    pass


class B(O):

    def __init__(self, cache):
        self.cache = cache


class B1(B):

    def p(self):
        self.cache.add_to_cache("32", "something something")


class B2(B):

    def p(self):
        self.cache.get_from_cache("52",  "something else")

对于B及其子类,我想创建一个缓存。此类(B、B1、B2)的所有实例都使用相同的缓存

为了简单起见,假设缓存只是一个dict

c = {}

a = A(c)
b1 = B() - needs c
b1.p()
b2 = C() - needs c
b2.p()

print(cache) 

当然,上面的例子是错误的,因为每个实例的缓存都不同

胃痛应该是:

{
"32", "something something"
"52":  "something else"
}

2条回答

另一种方法是使用CaseService作为可注入的单服务,我认为这是一个更好的实践。 Read this first for a code/syntax solution to your direct question,或继续阅读具有更好设计的解决方案

class O(object):
    pass

class CacheService(object):
    __instances = {}

    @staticmethod
    def getinstance(owner_id):
        if owner_id not in CacheService.__instances:
            CacheService.__instances[owner_id] = CacheService(owner_id)
        return CacheService.__instances[owner_id]

    def __init__(self, owner_id):
        self._owner_id = owner_id
        self._owner_query = CacheService.__name__ + self._owner_id
        self._cache = {}

    def put_in_cache(self, key, value):
        self._cache[self._owner_query + str(key)] = value

    def get_from_cache(self, key):
        return self._cache.get(self._owner_query + str(key), "the_default")


class B(O):
    def __init__(self):
        self._cache = CacheService.getinstance(B.__name__)

class B1(B):
    def __init__(self):
        super(B1, self).__init__()

    def p(self):
        val1 = self._cache.get_from_cache("a")
        print(val1)


class B2(B):
    def __init__(self):
        super(B2, self).__init__()

    def p(self):
        self._cache.put_in_cache("a", 2)

if __name__ == "__main__":
    b1 = B1()
    b2 = B2()

    b2.p()
    b1.p()

输出:

2


这仍然使用类变量,但在“日常代码”中隐藏它,并将其移动到“基础结构级别”。
我认为这更干净,因为现在您的类层次结构不应该处理自己的全局变量

要直接回答编程问题,请使用class variables

作为旁注,最好使用某种“CacheService”并将其注入构造函数,而不是使用继承和类变量。
关于这一点,见my other answer


使用类变量的代码如下:

class O(object):
    pass

class B(O):
    __cache = {}  # use your cache class if you want, I am using dict just for show
    def __init__(self):
        pass

    def _get_from_cache(self, key):
        return self._cache.get(key, "default1")

    def _put_in_cache(self, key, value):
        self._cache[key] = value


class B1(B):
    def __init__(self):
        super(B1, self).__init__()

    def p(self):
        val1 = self._get_from_cache("a")
        print(val1)


class B2(B):
    def __init__(self):
        super(B2, self).__init__()

    def p(self):
        self._put_in_cache("a", 2)

if __name__ == "__main__":
    b1 = B1()
    b2 = B2()

    b2.p()
    b1.p()

输出:

2


请注意_get_from_cache_put_in_cache是方法,但它们可以是@staticmethod,因为它们只访问类变量,并且它们的self从未被“真正”使用过__cache理论上可以由子级直接访问,但是_get_from_cache_put_in_cache使__cache私有,并为其提供受保护的API

相关问题 更多 >