on implementing a toy oop-system

Meredith Montgomery mmontgomery at levado.to
Fri Sep 23 16:59:12 EDT 2022


ram at zedat.fu-berlin.de (Stefan Ram) writes:

> Meredith Montgomery <mmontgomery at levado.to> writes:
>>Is that at all possible somehow?  Alternatively, how would you do your
>>toy oop-system?
>
>   Maybe something along those lines:
>
> from functools import partial
>
> def counter_create( object ):
>     object[ "n" ]= 0
> def counter_increment( object ):
>     object[ "n" ]+= 1
> def counter_value( object ):
>     return object[ "n" ]
>
> counter_class =( counter_create, counter_increment, counter_value )
>
> def inherit_from( class_, target ):
>     class_[ 0 ]( target )
>     for method in class_[ 1: ]:
>         target[ method.__name__ ]= partial( method, target )
>
> car = dict()
>
> inherit_from( counter_class, car )
>
> print( car[ "counter_value" ]() )
> car[ "counter_increment" ]()
> print( car[ "counter_value" ]() )
>
>   . The "create" part is simplified. I just wanted to show how
>   to make methods like "counter_increment" act on the object
>   that inherited them using "partial".

I really liked this idea.  I organized it my way.  Have a look.  (Thank
you for the lecture!)

--8<---------------cut here---------------start------------->8---
from functools import partial

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

def Car(maker):
  o = {"maker": maker, "state": "off"}
  inherit_from(Counter, o)
  def on(o):
    if o["is_on"]():
      raise ValueError("oh, no: car is already on")
    o["inc"]()
    print(f"{o['maker']}: bruum!")
    o["state"] = "on"
    return o
  o["on"] = partial(on, o)
  def off(o):
    if o["is_off"]():
      raise ValueError("oh, no: car is already off")
    print(f"{o['maker']}: spat!")
    o["state"] = "off"
    return o
  o["off"] = partial(off, o)
  def is_on(o):
    return o["state"] == "on"
  o["is_on"] = partial(is_on, o)
  def is_off(o):
    return o["state"] == "off"
  o["is_off"] = partial(is_off, o)
  return o

def main():
  car1 = Car("Ford")
  car2 = Car("VW")
  for i in range(5):
    car1["on"](); car1["off"]()
  for i in range(3):
    car2["on"](); car2["off"]()
  print(f"car turned on = {car1['get']()} ({car1['maker']})")
  print(f"car turned on = {car2['get']()} ({car2['maker']})")

## (*) How to inherit the methods from a class
## 
def inherit_from(C, target):
  o = C()
  for k, v in o.items():
    if callable(v):
      target[k] = partial(v, target)
    else:
      target[k] = v
--8<---------------cut here---------------end--------------->8---


More information about the Python-list mailing list