0

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!

1
  • Do you mean updated in database (asking because of the flask-sqlalchemy tag) or just the class property? Commented Jan 11, 2013 at 20:33

1 Answer 1

1

__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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.