First of all, you are adding the variable to the class test.a = a
. You should be adding it to the instance, self.a = a
. Because, when you add a value to the class, all the instances will share the data.
You can use __getattr__
function like this
class test(object):
def __init__(self, a = 0):
self.a = a
def __getattr__(self, item):
return None
t = test()
print t.a
print t.somethingelse
Quoting from the __getattr__
docs,
Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name.
Note: The advantage of __getattr__
over __getattribute__
is that, __getattribute__
will be called always, we have to handle manually even if the current object has the attribute. But, __getattr__
will not be called if the attribute is found in the hierarchy.