0

is it possible to have a single update method in a class that takes a variable as input for the name of the class variable to be updated.

for example. I have a class that mimics a mysql table and I want a generic update function that updates both the object and the mysql table

However obviously the last line isn't valid for updating the object is there a way that you can do that? Or will I need a function for each element.

class MyClass(object):
    def __init__(self, a, b, c, db_id):
        self.a = a
        self.b = b
        self.c = c
        self.db_id = db_id

    def update_field(self, field, value, cnx):
        update_query = "update my_table set %s = %s where id = %s"
        cursor = cnx.cursor(buffered=True)
        cursor.execute(update_query, (field, value, self.db_id))
        **self.field = value**

Thanks

DarK_FirefoX
  • 887
  • 8
  • 20
  • Why do you mean `self.field = value` is not valid? You are adding/updating the `MyClass` instance attribute `self.field` with a `value` value. – DarK_FirefoX Apr 03 '20 at 02:48
  • 1
    @DarK_FirefoX That sets the literal attribute `field` to `value`, not the attributed *named* by `field`. – chepner Apr 03 '20 at 02:52
  • You might want to consider using an ORM, which will take care of this type of thing for you. – chepner Apr 03 '20 at 02:53
  • This isn't related to the main part of your question, but your use of the term "class variable" is a bit misleading. The variables in the code you show are mostly *instance* variables, a class variable would be accessed as `MyClass.foo`. It might help your question be more easily understood if you used terminology more consistent with general practices! – Blckknght Apr 03 '20 at 02:55
  • @chepner, That's what he meant, I did not quite understand it. – DarK_FirefoX Apr 03 '20 at 02:56
  • Sorry I am new to Python and don't know the correct terminology. Thanks Blckknght now I know a little bit more than I did. – Brad Flintoff Apr 03 '20 at 03:06

1 Answers1

4

You can use setattr to set an attribute based on its string name, i.e.:

def update_field(self, field, value, cnx):
    update_query = "update my_table set %s = %s where id = %s"
    cursor = cnx.cursor(buffered=True)
    cursor.execute(update_query, (field, value, self.db_id))
    setattr(self, field, value)

The line setattr(self, field, value) will set the value of the field attribute of self to value.

dspencer
  • 4,297
  • 4
  • 22
  • 43