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 に答える