Call a class A method from a class B instance? Do I miss something?

jfong at ms4.hinet.net jfong at ms4.hinet.net
Fri Aug 18 03:25:20 EDT 2017


Rick Johnson at 2017/8/18 UTC+8 AM 11:43:06 wrote:
> jf... at ms4.hinet.net wrote:
> > I study some codes of a tutorial about tkinter
> >
> > [snip code]
> >
> > My question is that the object which was left by
> > callit(self.demoenter_callback, tag) is a callit instance,
> > and the method it calls is a DemoMainWindow's method. How
> > it is possible?
> 
> Why would it _not_ be possible? Functions are first class
> objects, after all. Google it.
> 
> All the code is doing here is passing around a function
> reference and argument list like a baton in a foot race. No
> real magic here, just a lot of academic smoke and mirrors
> really. Or maybe this is more like a rat maze? Or a hot
> potato? Opinions may vary...
> 
> But short of obfuscation for the _sake_ of obfuscation, i
> don't understand what the tutorial author is intending to
> teach you here. Sheesh, the same goal could be achieved much
> more clearly by wrapping the argument-laden callback in an
> anonymous function or using a functools.partial, as the
> _true_goal_ here is to avoid premature execution of the
> argument-laden callback.
> 
> I absolutely detest superfluity!
> 
> --

According to the explanation above Ian had done, this method was already bound by "self". To set my mind ease, I follow your suggestion and implement a closure to replace the class:

    def callit(function, *args):
        def inner(*ignored):
            return function(*args)
        return inner

or even a lambda to get rid of callit:

    lambda *ignored, a=tag: self.demoenter_callback(a)

I didn't try functools.partial but I think it will work too.

Thanks for your point of view.

--Jach




More information about the Python-list mailing list