AttributeError in "with" statement (3.2.2)

Steve Howell showell30 at yahoo.com
Thu Dec 15 08:35:55 EST 2011


On Dec 14, 9:01 pm, Steven D'Aprano <steve
+comp.lang.pyt... at pearwood.info> wrote:
> [...]
> So what are methods? In Python, methods are wrappers around functions
> which automatically pass the instance to the inner function object. Under
> normal circumstances, you create methods by declaring functions inside a
> class, but that's not the only way to create methods, and it is not the
> only place they can be found.
>

I've always understood methods as basically function wrappers that
pass in the instance, so it's good to hear somebody else formulate it
that way.

For the special methods like __enter__ and __exit__, the tricky part
isn't understanding what would happen once the methods were called;
the tricky part is getting them to be called in the first place, if
they were not declared inside the class or attached to the class.

import types

class Blank:
  pass

foo = Blank()
foo.name = "foo1"
foo.__exit__ = types.MethodType(lambda self, *args: print(self.name),
foo)

foo.__exit__() # works like a method in python3, prints foo1
with foo:
  pass



More information about the Python-list mailing list