• CONTEST ALERT - Experience the power of DDR5 memory with Kingston Click for details

Python: why it worked later, function keywords:

Status
Not open for further replies.

ravi.xolve

Broken In
The following code didn't work:

class X(object):
def f(self, **kwds):
print kwds
try:
print kwds['i'] * 2
except KeyError:
print "unknown keyword argument"
self.g("string", kwds)

def g(self, s, **kwds):
print s
print kwds

if __name__ == "__main__":
x = X()
x.f(k = 2, j = 10)

However the following did:

class X(object):
def f(self, **kwds):
print kwds
try:
print kwds['i'] * 2
except KeyError:
print "unknown keyword argument"
self.g("string", **kwds)

def g(self, s, **kwds):
print s
print kwds

if __name__ == "__main__":
x = X()
x.f(k = 2, j = 10)

Please explain
 

QwertyManiac

Commander in Chief
Its because your g function is set to accept one formal parameter and optional keyword arguments after it. So its set to accept only 2 arguments inside the class, the class itself and s.

In Python, the * is usually used to "unpack" a tuple or a list for passing them as arguments to a function, while the ** is used over dictionaries to make them deliver keyword arguments over to other functions that accept it as the last parameter.

For more, there's Python documentation reference.
 
Status
Not open for further replies.
Top Bottom