如何使用变量名更新类变量



是否可以在一个类中使用一个更新方法,该方法将一个变量作为要更新的类变量名称的输入。

例如。我有一个模拟mysql表的类,我想要一个通用的更新函数来更新对象和mysql表

然而,很明显,最后一行对更新对象无效,有没有办法做到这一点?或者我需要每个元素都有一个函数。

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**

感谢

您可以使用setattr根据其字符串名称设置属性,即:

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)

setattr(self, field, value)将把selffield属性的值设置为value

最新更新