每次更新对象时,使用flask sqlalchemy执行方法

时间:2013-01-11 18:32:07

标签: python sqlalchemy flask flask-sqlalchemy

每次更新类成员时执行的方法名称是什么?

例如,在实例化对象时运行 init

class Foo(db.Model)
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(50))

    def __init__(self, description):
        self.description = description

我想在每次更新Foo对象时运行此类的方法。

在这里阅读了python类之后:

http://www.rafekettler.com/magicmethods.html

我认为我正在寻找的方法看起来像下面的东西(但还没有让它工作):

class Foo(db.Model)
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(50))

    def __init__(self, description):
        self.description = description

    def __call__(self, description):
        print 'obj is getting updated!'
        self.description = description

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

当您想要使对象的实例可调用时,使用

__call__,就像函数一样:

class Foo(object):
    def __init__(self, foo):
        self.foo = foo

    def __call__(self):
        return 'foo is {}!'.format(self.foo)

foo = Foo('bar')
print foo()    # Note that we're calling instance of Foo as if it was a function.

您可能想要的是__setattr__,当将值分配给对象的属性时会调用它:

class Foo(db.Model):
    # ...

    def __setattr__(self, name, value):
        # Call the parent class method first.
        super(Foo, self).__setattr__(name, value)
        print 'Value {!r} was assigned to attribute {}'.format(value, name)