frazman
frazman

Reputation: 33213

Writing a class inside a function in Python

I am trying to write a class inside a function... something like the following:

def func(**args):
   class BindArgs(object):
       foo = args['foo']
       print 'foo is ', foo
       def __init__(self,args):
          print " hello, I am here"

f = func(foo=2)

I was hoping that print will be executed.. but the init block is not being executed... though print 'foo is ' stub runs... What am I missing?

I am trying to understand, how does this module works (https://github.com/tweepy/tweepy/blob/master/tweepy/binder.py)?

Upvotes: 1

Views: 7051

Answers (3)

Oliver W.
Oliver W.

Reputation: 13459

That's because init is only executed when an instance of the class is being created, which is not happening in your function. You have to explicitly call BindArgs(someobject) for that. However, the class is being defined when you call func, so the contents of the class definition are executed.

Upvotes: 0

jjwon
jjwon

Reputation: 204

Inside func you're not actually initializing a new BindArgs object, so Python will not call the __init__() function. However, it does read through the class definition to use it inside the function scope, so it does execute the other print statement...

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113930

You just need to return an instance of the class...

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=3)

If you wanted to call it later like in the example from the comments, you could just do

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

f = func(foo=3)
f(args="yellow")

Upvotes: 2

Related Questions