如何在Python中返回字典元素时避免递归错误?

huangapple go评论67阅读模式
英文:

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...

huangapple
  • 本文由 发表于 2023年4月4日 17:33:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927766.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定