Jul-01-2020, 06:32 AM
(This post was last modified: Jul-01-2020, 06:50 AM by Gribouillis.)
Skaperen Wrote:would it not be good enough in this case to just do return type(self).close?Assuming that you want the following interface
x = topen('foo') x.close()then
x.close
needs to remember both the instance x
and the function object close
. That's where bound instance methods come in play. They contain basically an instance and a function and when they are called, they insert the instance as the first argument of the function. The call to types.MethodType()
creates the instance method.If you return only
type(self).close
, that is to say topen.close
in our case, this value does not remember the instance self. You would need to call x.close(x)
or get a missing argument error.Using
type(self)
instead of topen
allows self to be an instance of a subclass of topen if someone ever defines one. This subclass could potentially overwrite the close method.