0

The following raises an AttributeError: 'objval' object has no attribute 'testitem'

class objval(object):
    def __init__(self):
        self.testitem = 1
    def __setattr__(self, key, value):
        print('setattr: ' + str(key) + '=' + str(value))

testobj = objval()
print(testobj.testitem)

All though when removing def __setattr__(self, key, value): printing testobj.testitem now properly outputs the value.

1 Answer 1

3

You are overriding the setattr method of your class object. Like this it works and puts out your attribute. I just added the super method to let your object execute the original setattr method after your changes:

class objval(object):
    def __init__(self):
        self.testitem = 1

    def __setattr__(self, key, value):
        print('setattr: ' + str(key) + '=' + str(value))
        super(objval, self).__setattr__(key, value)

testobj = objval()
print(testobj.testitem)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This seems like strange behavior to me as I am looking up the value not changing it.
np! It is not strange. If you would delete the method your objval class will still own a method called __ setattr __. And this method does something (return something or change a class attribute etc.) but when you now write a methode with the exact same name you will override your initial method so nothing gets returned or no attribute gets changed. but if you use super() in the end you basically go along the inheritance tree of your class to the next class with this method __ setattr __ and it gets executed. If you are interested in it look the super method up or look at class inheritance.

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.