1

I'm learning python, trying to figure out how does this code actually work:

def func(**args):
    class BindArgs(object):
       foo = args['foo']
       print 'foo is ', foo
       def __init__(self,args):
           print "hello i am here"
    return BindArgs(args) #return an instance of the class

f = func(foo=2)

Output:

foo is 2 hello i am here

But it's very confused that in the argument of a function func(foo=2) that takes equation mark in it. Could you please explain how the flow works?

martineau
  • 119,623
  • 25
  • 170
  • 301
Jason
  • 3,166
  • 3
  • 20
  • 37
  • The answer from the link is that: in my example, `args == 'foo' ` and `args['foo'] == 2`. Quick question, if class `GindArgs(object)` could take type `**args` as argument, does that mean regular class could actually take "keyword (dictionary)" as argument too? – Jason Dec 06 '17 at 22:33
  • Yes, functions and therefore class constructions can get a dictionary as their arguments. – Happy Ahmad Dec 07 '17 at 10:17

1 Answers1

1

Here is an abstract: You call the function func and pass a dictionary as the argument to it. In the func function, you define a class named BindArgs, and then in the return statement, you first make an object (instance) from the BindArgs class and then return that instance. Notice that the statement foo = args['foo'] get the key value of 'foo' from the args dictionary (that is 2 in your sample code). the init also will be run as the constructor of the class when you are creating an object.

Happy Ahmad
  • 1,072
  • 2
  • 14
  • 33