Reputation: 9033
what is the method name that gets executed every time a member of a class is updated?
for example, init is run when an object is instantiated:
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
i would like to add a method to this class that runs every time i update a Foo object.
after reading up on python classes here:
http://www.rafekettler.com/magicmethods.html
i thought that the method i was looking for would look something like the below (but haven't gotten it working yet):
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
thanks for the help!
Upvotes: 0
Views: 1455
Reputation: 13533
__call__
is used when you want to make the instances of your object callable, just like functions:
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.
What you probably want is __setattr__
, which is called when a value is assigned to object's attribute:
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)
Upvotes: 1