英文:
How to avoid recursive error when returning python dict elements in python?
问题
以下是翻译好的代码部分:
假设你想将Python字典的元素作为类本身的属性返回,你可以这样实现:
class MyClass:
def __init__(self):
print(self.x)
self.metadata = {
"a": 42,
"b": 1,
}
def __getattr__(self, item):
if item in self.metadata:
return self.metadata[item]
else:
raise KeyError(f"No attribute {item} found.")
test = MyClass()
但是这个实现会创建一个递归错误。
英文:
Suppose you want to return elements of a python dictionary as attributes of the class itself, you might implement it as follows:
class MyClass:
def __init__(self):
print(self.x)
self.metadata = {
"a": 42,
"b": 1,
}
def __getattr__(self, item):
if item in self.metadata:
return self.metadata[item]
else:
raise KeyError(f"No attribute {item} found.")
test = MyClass()
But that implementation creates a recursive error.
答案1
得分: 1
代码部分不翻译。以下是翻译好的部分:
问题在于在__getattr__
方法中,它检查字典self.metadata
中是否存在某个元素item
,但是self.metadata
尚未定义!因此,通过获取属性self.metadata
时,它再次调用__getattr__
方法!
解决方法是首先检查metadata
属性是否存在。因此,__getattr__
方法将变为:
def __getattr__(self, item):
if "metadata" in self.__dict__ and item in self.metadata:
return self.metadata[item]
else:
raise KeyError(f"No attribute {item} found.")
因此,只有在类中存在属性metadata
时,它才会检查item
是否存在...
英文:
The problem here is that in the method __getattr__
it is checked if some element item
is in the dict self.metadata
which is not yet defined! So by getting the attribute self.metadata
it calls the __getattr__
method again!
The solution is to check if the metadata
attribute exists in the first place. So the __getattr__
method will become
def __getattr__(item):
if "metadata" in self.__dict__ and item in self.metadata:
return self.metadata[item]
else:
raise KeyError(f"No attribute {item} found.")
So only if the atribute metadata
exists in the class it will check if the item
exists...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论