Use the __getattr__ method, see documentation:
In [1]: class test(object):
...: a = 'hi'
...: def __getattr__(self, val):
...: print 'you are accessing ', val
...:
...:
In [2]: t = test()
In [3]: t.b
you are accessing b
In [4]: t.c
you are accessing c
In [5]: t.a
Out[5]: 'hi'
EDIT:
class test(object):
a = 'hi'
def msg(self, var, default='undefined'):
setattr(self, var, default)
return default
def __getattr__(self, val):
print 'attribute %s not found, setting..' % val
return self.msg(val)
>>> t = test()
>>> print t.a
'hi'
>>> print t.b
'attribute b not found, setting..'
'undefined'
>>> t.b = 'this is black magic'
>>> # notice no message is printed here about attribute not found
>>> print t.b
'this is black magic'
EDIT2:
>>> d = {'a': '1'}
>>> d.setdefault('b', 'b')
'b'
>>> d
{'a': '1', 'b': 'b'}
>>> d.setdefault('a', 'b')
'1'
>>> d
{'a': '1', 'b': 'b'}
AttribuiteErrorif you refer a variable which does not exist.