【问题标题】:What does __setattr__ do in this python code?__setattr__ 在这个 python 代码中做了什么?
【发布时间】:2011-03-19 09:35:04
【问题描述】:

这是我的代码:

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

【问题讨论】:

    标签: python get set


    【解决方案1】:

    问题是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
    

    【讨论】:

      【解决方案2】:

      这是一个错字。

      您要实现特殊方法__setattr__,而不是没有特殊含义的__serattr__。

      【讨论】:

        【解决方案3】:

        首先,该方法被称为__setattr__()。这是尝试进行属性分配的时候。比如当你这样做时:

        self[key] = value+1
        

        ...使您的特定调用(无限)递归!

        更好的方法是从object 派生您的类,即所谓的new-style class 并调用基类:

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

        我删除了您的 __getattr__() 实现,因为它没有任何价值。

        【讨论】:

          猜你喜欢
          • 2022-08-04
          • 2016-02-17
          • 2023-03-17
          • 2017-12-04
          • 1970-01-01
          • 1970-01-01
          • 2018-03-14
          • 2021-04-25
          • 1970-01-01
          相关资源
          最近更新 更多