描述符作为字典值

问题描述 投票:0回答:2

我有一个类似字典的对象,它在内部存储描述符:

 class MyDict(object):
    def __init__(self):
        dict.__init__(self)

    def __getitem__(self, key):
        v = dict.__getitem__(self, key)
        if hasattr(v, '__get__'):
           return v.__get__(None, self)
        return v

class MyDescriptor(object):
    def __init__(self, value, attrib={}):
        self.__value = value
        self.attrib= attrib

    def __get__(self, instance, owner):
        return self.__value

    def __set__(self, instance, value):
        self.__value = value

我希望能够执行以下操作:

d = MyDict()
d['1'] = MyDescriptor("123", {"name": "val"})
print d['1']                     # prints "123"
print d['1'].attrib["name"]      # prints "val"

我的课程无效。您能帮我吗?

python dictionary descriptor
2个回答
1
投票

您的解决方案看起来不必要地复杂,无法解决您的问题,除非有更多显示。为什么不简单地这样做:


1
投票

我不确定这是否可以解决您的用例,但是要达到您所说的结果,您可以简单地删除MyDict类并使用普通的dict

© www.soinside.com 2019 - 2024. All rights reserved.