on implementing a toy oop-system

Meredith Montgomery mmontgomery at levado.to
Fri Sep 23 21:08:16 EDT 2022


Chris Angelico <rosuav at gmail.com> writes:

> 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 :)

I started out this way, but I had to change direction to implement
inheritance: the difficulty with closures seems to be lexical scoping,
which makes it hard (or impossible) for me to move these closures to
another ``object''.  For instance, the nonlocal /n/ in /inc/ above is
forever bound to that closure; there seems to be no way to make /inc/
update some /n/ in another ``object'', which is needed in my conception
of inheritance.  I think Python would have to let me duplicate closures.
(Thanks for showing me /locals()/.)


More information about the Python-list mailing list