1

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)?

2
  • 2
    Why do you want to do this? Commented Jul 1, 2014 at 23:05
  • The link is broken (404). Commented Jan 16, 2022 at 1:19

3 Answers 3

2

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")
Sign up to request clarification or add additional context in comments.

5 Comments

im guessing with the _call method that is returned at the end ... but who knows Im not sure how thats invoked or used so I couldnt tell you
as expected user_point=bind_api(**kwargs); user_point() they call the binding later ... since bind_api returns a method call ...
Where is the above line of code.. is it in api.py file
thats how you invoke the api_bind point that you create ... im not sure where in the code that happens... and dont want to dig but thats how you invoke it ... if you edit that file and add print statements to __init__ you will see it does not invoke until you call the returned method ... which is exactly what you would expect
0

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...

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.