这个Python代码中的__setattr__作用是什么?

2 投票
3 回答
1863 浏览
提问于 2025-04-16 14:01

这是我的代码:

class fun:

    def __getattr__(self,key):
        return self[key]

    def __setattr__(self,key,value):
        self[key] = value+1
a = fun()
a['x']=1
print a['x']

然后出现的错误是:

AttributeError: fun instance has no attribute '__getitem__'

当我把它改成:

class fun:

    def __getattr__(self,key):
        return self.key

    def __setattr__(self,key,value):
        self.key = value+1
a = fun()
a.x=1
print a.x

错误变成了:

RuntimeError: maximum recursion depth exceeded

我该怎么办,我想得到 2

3 个回答

1

首先,这个方法叫做 __setattr__()。它是在你尝试给一个属性赋值的时候会被调用。比如,当你这样做的时候:

self[key] = value+1

...这会导致你的调用变成无限递归,也就是一直在重复自己!

更好的做法是让你的类继承自 object,这被称为 新式类,然后调用基类的方法:

class fun(object):

    def __setattr__(self,key,value):
        super(fun, self).__setattr__(key, value + 1)

a = fun()
a.x=1
print a.x

我把你的 __getattr__() 实现去掉了,因为它没有任何实际的价值。

3

这是一个打字错误。

你想要实现的是特殊方法 __setattr__,而不是 __serattr__,后者没有任何特别的含义。

7

这个问题在于 self.key = ... 这行代码会调用 __setattr__ 方法,这样就会导致无限循环。为了使用 __setattr__,你需要用其他方式来访问对象的属性。这里有两种常见的解决办法:

def __setattr__(self,key,value):
    # Access the object's fields through the special __dict__ field
    self.__dict__[key] = value+1

# or...

def __init__(self):
    # Assign a dict field to access fields set via __[gs]etattr__
    self.attrs = {}

def __setattr__(self,key,value):
    self.attrs[key] = value+1

撰写回答