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

Python 如何在不同类(继承自同一父类)的实例之间传递相同的变量(iterable),python,python-3.x,caching,class-variables,Python,Python 3.x,Caching,Class Variables,我想在不同类的实例之间传递一个变量(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.

我想在不同类的实例之间传递一个变量(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"
}

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

作为旁注,最好使用某种“CacheService”并将其注入构造函数,而不是使用继承和类变量。
有关此信息,请参见


使用类变量的代码如下:

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()
输出:

二,



请注意,
\u从\u缓存中获取\u
\u放入\u缓存中
都是方法,但它们可以是
@staticmethod
s,因为它们只访问类变量,而它们的
self
并没有“真正”被使用<代码> >缓存Case>代码,理论上可以直接由儿童访问,但是 GETyFasuxCux和PuthIn Casy使 SysCase私有,并给出了一个受保护的API。

< P>另一种方法是使用CaseService作为可注入的单服务,这是一个更好的实践。 ,或继续阅读具有更好设计的解决方案

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()
输出:

二,


这仍然使用类变量,但在“日常代码”中隐藏它,并将其移动到“基础结构级别”。

我认为这更干净,因为现在你的类层次结构不应该处理它自己的全局变量。

如果你想在不同的实例上共享数据,你应该将
缓存
作为一个类属性。