Something about python: __setattr__ and __getattr__




o = {


get b() { return this.a+1; },



o.c=8; alert(o.b);



When we assign o.c=8, o.a will become 8/2=4, and o.b will returns o.a+1=5. This is easy to understand.

But such setter and getter function has its limits. It can only define on the member which its name is known to us, it will not intercept the visit to undefined members, which may troubles us. And the member which getter function is defined cannot be visited, not through any means possible.

Python can, however. The following passages are extracted from python 2.6.2 documentation:

object.__getattr__(self, name)


object.__setattr__(self, name, value)


So, we can write our code like this:

class DOMObject(object):
    def __setattr__(self, name, val):
        if name == 'src': #do something
        self.__dict__[name]=val # this will assign the real, despite __setattr__
    def __getattr__(self, name):
        return None

It means that when the src of a DOM object is assigned, do something (output for analyzation, for example), and when visit a member of the object that doesn't exist, returns null instead of raise an error (this is what javascript do, but not what python do normally).

We can use this two methods to do more, such as use window as global object (it really troubles us a long time). We will update a blog about this soon.