Skip to content

Data Model

Satish Goda edited this page Jun 11, 2016 · 3 revisions

Customizing attribute access

getattr, setattr

class Foo(object):
    X = 100
    def __init__(self):
        self.x = 10
    
    def __getattr__(self, attr):
        _defs = {'y': 20, 'z': 30, 'a': 800}
        if attr in _defs:
            return _defs[attr]
        else:
            raise AttributeError("Attribute '{0}' does not exist".format(attr))

    def __setattr__(self, attr, value):
        super(Foo, self).__setattr__(attr, value)

f1 = Foo()

print f1.X
print f1.x

print f1.y

f1.y = 200

print f1.y

print f1.t

print hasattr(f1, 'x') is True
print hasattr(f1, 't') is False
Clone this wiki locally