on implementing a toy oop-system

Chris Angelico rosuav at gmail.com
Fri Sep 23 18:06:31 EDT 2022


On Sat, 24 Sept 2022 at 07:52, Meredith Montgomery
<mmontgomery at levado.to> wrote:
>
> def Counter(name = None):
>   o = {"name": name if name else "untitled", "n": 0}
>   def inc(o):
>     o["n"] += 1
>     return o
>   o["inc"] = inc
>   def get(o):
>     return o["n"]
>   o["get"] = get
>   return o
>

Want a neat demo of how classes and closures are practically the same thing?

def Counter(name=None):
    if not name: name = "untitled"
    n = 0
    def inc():
        nonlocal n; n += 1
    def get():
        return n
    return locals()

Aside from using a nonlocal declaration rather than "self.n", this is
extremely similar to classes, yet there are no classes involved.

A class statement creates a namespace. The locals() function returns
the function's namespace.

Each call to Counter() creates a new closure context, just like each
call to a constructor creates a new object.

There's very little difference, at a fundamental level :)

ChrisA


More information about the Python-list mailing list