简体   繁体   English

Python ** kwargs和self作为参数

[英]Python **kwargs and self as an argument

I don't have much experience in python but I am studying **kwargs . 我没有python的丰富经验,但是我正在研究**kwargs

Afer reading a lot I understood somethings about **kwargs but I have a small problem or I am not understanding something correct. 大量阅读后,我对**kwargs有所了解,但是我遇到了一个小问题, 或者我不了解正确的东西。

So this works : 所以这有效

def test_var_kwargs(farg, **kwargs):
    print "formal arg:", farg
    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

test_var_kwargs(farg=1, myarg2="two", myarg3=3)

And prints: 并打印:

formal arg: 1 形式参数:1

another keyword arg: myarg2: two 另一个关键字arg:myarg2:两个

another keyword arg: myarg3: 3 另一个关键字arg:myarg3:3

But if that function was an instance function then self would have to be included: 但是,如果该函数是实例函数,则必须包含self

def test_var_kwargs(self, farg, **kwargs):
        print "formal arg:", farg
        for key in kwargs:
            print "another keyword arg: %s: %s" % (key, kwargs[key])

self.test_var_kwargs(farg=1, myarg2="two", myarg3=3)

But this produces an error : 但这会产生一个错误

TypeError: test_var_kwargs() takes exactly 2 arguments (1 given)

I understand that I have to pass self like: 我了解我必须像这样通过自我:

self.test_var_kwargs(self, farg=1, myarg2="two", myarg3=3)

Why do I have to include self as an argument in the class instance's method? 为什么我必须在类实例的方法中包括self作为参数?

You cannot use farg as keyword argument in that case; 在这种情况下,不能将farg用作关键字参数。 it cannot be interpreted as both a positional and a keyword argument, Python interprets it as a keyword argument in this case. 它不能同时解释为位置参数关键字参数,在这种情况下,Python会将其解释为关键字参数。

Use 采用

self.test_var_kwargs(self, 1, myarg2="two", myarg3=3)

instead. 代替。

Functions act as descriptors; 函数充当描述符; when looked up on an instance, they get wrapped in a new object called a method, which automatically adds the instance as a first argument to the function when called. 在实例上查找时,它们被包裹在称为方法的新对象中,该对象在调用时自动将实例作为第一个参数添加到函数中。 This wrapper essentially does this: 这个包装器基本上是这样做的:

class Method(object):
    def __init__(self, function, instance, cls):
        self.func = function
        self.instance = instance
        self.cls = cls

    def __call__(self, *args, **kw):
        return self.func(self.instance, *args, **kw)

Your farg keyword argument is then lumped under the **kw catchall and passed on to the underlying function, with *args left empty. 然后,将您的farg关键字参数集中在**kw catchall下,并传递给基础函数,而*args保留为空。

But the test_var_kwargs method you defined has one positional argument (next to self , and thus an exception is raised. 但是您定义的test_var_kwargs方法只有一个位置参数( self旁边),因此引发了异常。

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

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