我有一个用例,我想在字典中存储键值对。 我面临的问题是我的键是“复制”。因此,插入“复制”键后,我无法通过 getattr 方法访问它,因为它总是返回 dict 的复制方法。
我无法在 dict 上使用 get 方法,因为我的代码不知道正在传递的对象的类型。因此,我继续使用 getattr,这是访问属性的通用函数。
我还创建了一个继承自 dict 的自定义类并编写了 getattribute 但阻止了对方法的访问
class DictLike(dict):
def __getattribute__(self, k):
try:
return self[k]
except KeyError:
getattr(super(DictLike, self), k)
def paste(self):
return "Test"
a = DictLike()
a['copy'] = 1;
a['state'] = 'completed'
print(getattr(a, 'copy')) // prints 1
print(a.paste()) // this does not works
b = {'copy': 1}
print(b.get('copy')) \\ 1
getattr(b, 'copy') \\ function
有什么办法可以解决这个问题吗?
最佳答案
这是可行的解决方案:
class DictLike(dict):
def __init__(self, *args, **kw):
super(DictLike, self).__init__(*args, **kw)
self.itemlist = super(DictLike, self).keys()
def __getattribute__(self, k):
try:
return self[k]
except Exception as e:
return super().__getattribute__ (k)
def paste(self):
return "Test"
a = DictLike()
a['copy'] = 1
a['state'] = 'completed'
print(getattr(a, 'copy'))
print(a.paste())
关于python - 有没有一种方法可以在 python 中创建自定义字典而无需复制方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56770122/