0

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

例如,在实例化对象时运行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

谢谢您的帮助!

4

1 回答 1

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)
于 2013-01-11T20:20:35.320 回答