Writing A Class Inside A Function In Python
I am trying to write a class inside function.. something like following: def func(**args): class BindArgs(object): foo = args['foo'] print 'foo is ', foo de
Solution 1:
you just need to return an instance of the class ...
deffunc(**args):
classBindArgs(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
deffunc(**args):
classBindArgs(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")
Solution 2:
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..
Solution 3:
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.
Post a Comment for "Writing A Class Inside A Function In Python"