在列方法中接受列表作为参数 - 未定义名称“selected_fields”

时间:2017-02-09 21:00:57

标签: python python-3.x

我有一个类Database,如下所示: 已更新

    class Database():
        query_stmt_list = ['SELECT','INSERT','UPDATE','DELETE','FROM','WHERE']

        def db_select(self, *selected_fields, **kwargs):
            self.selected_fields = selected_fields = list(selected_fields)
            self.table = (kwargs['table']
                          if 'table' in kwargs 
                          else selected_fields.pop())
            self.where_field = (kwargs['where_field']
                                if 'where_field' in kwargs
                                else selected_fields.pop())
            try:
                with db.cursor() as cursor:
                    sql_tld_id_query = self.query_stmt_list[0]+ selected_fields + self.query_stmt_list[4] + table + self.query_stmt_list[5] + where_field + '=' + 'www.website.com'    
            except Exception as gatherid_err:
                print("exception was {}".format(gatherid_err))
                db.rollback()

我通过以下方式调用此方法:

dbclass = Database()
dbclass.db_select(*selected_fields, table='tld', where_field='name')

但我收到错误:

  line 51, in <module>
    dbclass.db_select(*selected_fields, table='tld', where_field='name')
NameError: name 'selected_fields' is not defined

谢谢。

1 个答案:

答案 0 :(得分:0)

如果你想像selected_fields那样解包“dbclass.db_select(*selected_fields, 'tld', 'name')”变量,你最好:

  1. 安装了Python 3.5 / 3.6。这个函数调用的语法在Python 3.4和之前是错误的。 3.5引入的新功能称为“附加解包概括”,它允许用户放置由可迭代解包操作符装饰的变量,即单个星号“*”,before other variables

  2. 修改您的db_select方法以应用可在*selected_fields之后接受两个额外参数的技巧:

    def db_select(self, *args):
        self.selected_fields = selected_fields = list(args)
        self.where_field = selected_fields.pop()
        self.table = selected_fields.pop()
        ...
    
  3. 如果您希望db_select方法也接受命名参数,例如dbclass.db_select(*selected_fields, table='tld', where_field='name'),可以这样做:

        def db_select(self, *args, **kwargs):
            self.selected_fields = selected_fields = list(args)
            self.where_field = (kwargs['where_field']
                                if 'where_field' in kwargs
                                else selected_fields.pop())
            self.table = (kwargs['table']
                          if 'table' in kwargs
                          else selected_fields.pop())
            ...