2013-01-11 55 views
0

每次更新類的成員時,會執行哪些方法名稱?當對象被實例化每次更新對象時,應使用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 

感謝您的幫助!當你想使你的對象的情況下可調用

+0

你的意思是更新數據庫(因爲flask-sqlalchemy標籤問)或只是類屬性? – plaes

回答

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) 
相關問題