Python Forum
iundefined is really defined
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
iundefined is really defined
#6
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.
Reply


Messages In This Thread
iundefined is really defined - by Skaperen - Jun-30-2020, 03:07 PM
RE: iundefined is really defined - by Gribouillis - Jun-30-2020, 06:22 PM
RE: iundefined is really defined - by Skaperen - Jun-30-2020, 11:28 PM
RE: iundefined is really defined - by bowlofred - Jun-30-2020, 11:41 PM
RE: iundefined is really defined - by Skaperen - Jul-01-2020, 01:06 AM
RE: iundefined is really defined - by Gribouillis - Jul-01-2020, 06:32 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  python library not defined in user defined function johnEmScott 2 5,077 May-30-2020, 04:14 AM
Last Post: DT2000

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020