2

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

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

Comments

3

It's a typo.

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

Comments

1

Firstly, the method is called __setattr__(). It is when an attribute assignment is attempted. Such as when you do:

self[key] = value+1

...making your particular call (infinitely) recursive!

A better way to do this would be to derive your class from object, a so-called new-style class and call the base class:

class fun(object):

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

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

I removed your __getattr__() implementation, since it did nothing of any value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.