Prevent self being passed to a function stored as a member variable?

S

Sandra-24

How can you prevent self from being passed to a function stored as a
member variable?

class Foo(object):
def __init__(self, callback):
self.func = callback

f =Foo(lambda x: x)
f.func(1) # TypeError, func expects 1 argument, recieved 2

I thought maybe you could do this:

class Foo(object):
def __init__(self, callback):
self.func = staticmethod(callback) # Error, staticmethod not
callable

Somebody (maybe everybody other than myself) here must know?

Thanks,
-Sandra
 
Q

Qiangning Hong

How can you prevent self from being passed to a function stored as a
member variable?

class Foo(object):
def __init__(self, callback):
self.func = callback

f =Foo(lambda x: x)
f.func(1) # TypeError, func expects 1 argument, recieved 2

Do you really get that error? I got the following in my python shell:

..>>> class Foo(object):
..... def __init__(self, callback):
..... self.func = callback
.....
..>>> f = Foo(lambda x: x)
..>>> f.func(1)
1
 
S

Sandra-24

Qiangning said:
Do you really get that error?

Sorry, my bad. You're correct of course. I had accidentally passed an
object, by naming it the same as the function, instead of my function,
and the object had __call__ defined, and took exactly two parameters,
just like my function, but one of them beign self. So when I passed two
arguments, it got three, and that's how I was confused into thinking
self was being passed to my function (because it was, but not to my
function.) All a big foulup on my part. I might have worked on that
problem for a while before figuring it out, thanks!

-Sandra
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top