简体   繁体   English

Python:使用** kwargs的类定义

[英]Python : class definition with **kwargs

When trying to instantiate the following class I am getting the following error : 尝试实例化以下类时,我收到以下错误:

"TypeError: __init__() takes exactly 2 arguments (3 given)"

Do you know what would be the issue ? 你知道这会是什么问题吗? Here is the class definition : 这是类定义:

class db_create_table():
        '''
            doc here
        '''
        def __init__(self,TableName, **kwargs ):
            self.TableName = TableName
            for k,v in kwargs.iteritems():
                setattr(self, k, k)


schema =  {"id" : { "type":"Integer", "primary":"primary_key=True", "unique":"unique = True"},
           "col1" :  { "type":"String()", "primary":"primary_key=False", "unique":"unique = True"},
           "col2" :  { "type":"String()", "primary":"primary_key=False", "unique":"unique = False"},
           "col3" :  { "type":"String()", "primary":"primary_key=False", "unique":"unique = False"},
           "col4" :  { "type":"String()", "primary":"primary_key=False", "unique":"unique = False"},
           "CreatedOn" :  { "type":"DateTime", "primary":"", "unique":"unique = False"},
           "UpdatedOn" :  { "type":"DateTime", "primary":"primary_key=False", "unique":"unique = False"},
                            }


db_create_table('Table1', schema)

In order to pass schema and to unpack it into **kwargs , you have to use **schema : 为了传递schema并将其解压缩到**kwargs ,你必须使用**schema

db_create_table('Table1', **schema)

Explanation: The single asterisk form ( *args ) unpacks a sequence to form an argument list, while the double asterisk form ( **kwargs ) unpacks a dict-like object to a keyworded argument list. 说明:单个星号形式( *args )解包序列以形成参数列表,而双星号形式( **kwargs )将类似dict的对象解压缩到keyworded参数列表。

Without any asterisk, the given object will directly passed as it is, without any unpacking. 没有任何星号,给定的对象将直接传递,而不进行任何解包。

See also how to use *args and **kwargs in Python . 另请参阅如何在Python中使用* args和** kwargs

The kwargs parameter in the function is capturing keyword arguments; 函数中的kwargs参数是捕获关键字参数; you are passing a single object without unpacking it. 您正在传递单个对象而不解压缩它。

You either need to pass it with **, so it gets unpacked, or add *args to the function definition. 您需要使用**传递它,因此它会被解压缩,或者将* args添加到函数定义中。 For example, look how the function interprets the arguments: 例如,查看函数如何解释参数:

def func(*args, **kwargs):
    print args
    print kwargs

func(arg)
func(*arg)
func(*arg, keyword='key')

output: 输出:

(('one', 'two'),)  -- passed as arg, single element
{}
('one', 'two')  -- passed as *arg - object is unpacked
{}
('one', 'two')
{'keyword': 'key'}  -- keyword arg looks like that

As you pass positional args with *args, you can pass keyword args with **kwargs when calling the func. 当您使用* args传递位置参数时,您可以在调用func时传递带有** kwargs的关键字参数。

You're passing two args , but are only catching kwargs . 你传递了两个args ,但只是抓住了kwargs
schema is being passed as a positional argument which would be caught by *args ; schema作为位置参数传递,该参数将被*args捕获; if you wanted it to be caught by **kwargs you'd have to pass it as keyword argument: 如果你想让它被**kwargs捕获,你必须将它作为关键字参数传递

db_create_table('Table1', schema=schema)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM