Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does __setattr__ do in this python code?

Tags:

python

set

get

this is my code:

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']

and the error is :

AttributeError: fun instance has no attribute '__getitem__'

when i change it to :

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

the error is :

RuntimeError: maximum recursion depth exceeded

what can I do, I want get 2

like image 241
zjm1126 Avatar asked Apr 25 '26 10:04

zjm1126


2 Answers

The problem is that self.key = ... invokes __setattr__, so you end up in an infinite recursion. To use __setattr__, you have to access the object's field some other way. There are two common solutions:

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
like image 118
Marcelo Cantos Avatar answered Apr 27 '26 00:04

Marcelo Cantos


It's a typo.

You want to implement the special method __setattr__, and not __serattr__ which has no special meaning.

like image 23
Mark Byers Avatar answered Apr 27 '26 00:04

Mark Byers