2

出于缓存/持久性的原因,我希望为基类的任意大的子类树(它本身永远不会创建)获取唯一的可哈希地址。这是目前的情况:

OBJECT_CACHE = dict()

class Base(object):
    def __new__(cls, *args, **kwargs):
        # calculate class_addr here?
        obj = OBJECT_CACHE.get(class_addr)
        if obj is None:
            obj = super(Base, cls).__new__(cls, *args, **kwargs)
            OBJECT_CACHE[class_addr] = obj
        return obj

但我不确定获得这样一个 id 的最佳方法是什么。我的概念是它看起来像下面这样:

Base:          # no id
    F          # id = 'f'
    A:         # id = 'a'
        E      # id = 'a.e'
        B:     # id = 'a.b'
            C  # id = 'a.b.c'
            D  # id = 'a.b.d'

我想过尝试一些带有属性的东西,super()但理想情况下,子类只包含一行,比如my_id = 'e'. 提前致谢!

4

1 回答 1

2

您正在寻找的是cls.mro()

OBJECT_CACHE = dict()
class Base(object):
    def __new__(cls, *args, **kwargs):
        class_addr = cls.name()
        obj = OBJECT_CACHE.get(class_addr)
        if obj is None:
            obj = super(Base, cls).__new__(cls, *args, **kwargs)
            OBJECT_CACHE[class_addr] = obj
        return obj
    @classmethod
    def name(cls):
        names = [k.__name__.lower() for k in cls.mro() 
                if k != Base and issubclass(k, Base)]
        return '.'.join(names[::-1])


class F(Base): pass
class A(Base): pass
class E(A): pass
class B(A): pass
class C(B): pass
f = F()
a = A()
e = E()
b = B()
c = C()
print(OBJECT_CACHE.keys())

产量

['a', 'a.e', 'a.b.c', 'a.b', 'f']
于 2013-03-17T17:21:14.013 回答