开发者

Detecting when a new attribute is added to a object in Python?

I would like to have a special obj that does the following:

obj.newly_created_attribute = some_value

Obviously, all objects will allow this. But I 开发者_如何学JAVAwould like the previous code to automatically call a method when newly_created_attribute is not yet a attribute of obj. In my particular case, I wish to set up a custom get and set method for obj.newly_created_attribute (a property now).

Is there any way to do this? Some way to specify a callback that will be run whenever a new attribute is added to a object?


You can accomplish this by overriding __setattr__:

class SomeClass(object):
    def __setattr__(self, name, value):
        if not hasattr(self, name):
            print "new attribute", name
            # do stuff here
        return object.__setattr__(self, name, value)


__setattr__ will help you there:

Called when an attribute assignment is attempted. This is called instead of the normal mechanism (i.e. store the value in the instance dictionary). name is the attribute name, value is the value to be assigned to it.

#!/usr/bin/env python

class Klass(object):

    def __setattr__(self, name, value):
        if not hasattr(self, name):
            self.on_first_setattr()
        return object.__setattr__(self, name, value)

    def on_first_setattr(self):
        print "I am just a callback and my story's seldom told."

obj = Klass()
obj.some_attr = 1 # will call callback
obj.some_attr = 2 # no output


Overload __setattr__. Example:

class Foo(object):
    def __setattr__(self, attr, val):
        print "setattr"
        if attr not in self.__dict__:
            print "new attr:", attr
            self.__dict__[attr] = val
        else:
            print "extant attr:", attr
            self.__dict__[attr] = val
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜