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
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)
answered Jul 9, 2020 at 9:27
MisterNox
1,4652 gold badges10 silver badges22 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Quint
Thanks! This seems like strange behavior to me as I am looking up the value not changing it.
MisterNox
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.
lang-py