CKTIS / Python
Object model and composition
An object can hold another object in an instance attribute and delegate work to it.
Version: Python 3.14; repository image, production runtime not attested
Syntax
class Report:
def __init__(self, sink):
self.sink = sinkAn object can hold another object in an instance attribute and delegate work to it.
A bound method supplies the instance as self. A list created inside __init__ belongs to that Sink instance. A list declared in the class body would be a shared class attribute.
Two reports refer to one sink and see ['one']. A fresh Sink has its own [].
class Box:
def __init__(self, value): self.value=value
def read(self): return self.value
a,b=Box(2),Box(3)
assert a.read.__self__ is a and a.read.__func__ is Box.read
assert (a.read(),b.read())==(2,3)
class Shared:
items=[]
x,y=Shared(),Shared()
x.items.append('shared')
assert y.items==['shared']
Examples
class Sink:
def __init__(self):
self.rows = []
class Report:
def __init__(self, sink):
self.sink = sink
def put(self, text):
self.sink.rows.append(text)
sink = Sink()
a, b = Report(sink), Report(sink)
a.put("one")
print(b.sink is sink, b.sink.rows, Sink().rows)
Result
True ['one'] []
Two reports refer to one sink and see ['one']. A fresh Sink has its own [].