instcntr5.py

download

#!/usr/bin/env python2.3
# -*- coding: Latin-1 -*-
""" Black-Box-Erweiterung der Klasse Super um einen Instanzenzähler"""

# importiere Messenger und Requester oder definiere wie hier geschehen:
class Messenger:
"Broadcast messages to registered receivers"

target_dict = {}

def __call__(self,msg_name,*arglist,**argdict):
for handler in self.target_dict[msg_name]:
handler(*arglist,**argdict)

def register(self,msg_name,handler):
self.target_dict.setdefault(msg_name,[]).append(handler)

class Requester:
"Request message from registered address"
request_dict = {}

def __call__(self,address,req_name,*arglist,**argdict):
return self.request_dict[address][req_name](address,*arglist,**argdict)

def register(self,address,req_name,handler):
self.request_dict.setdefault(address,{req_name:handler})

# importiere Cntr_class oder definiere wie hier geschehen:
class Cntr_class:
cntr_dict = {}

def __call__(self,identifier):
k = identifier
self.cntr_dict[k] = self.cntr_dict.setdefault(k,0) + 1

def get_cntr(self,identifier):
return self.cntr_dict[identifier]

get_cntr = classmethod(get_cntr)

# Beispiel beginnt von hier ab:
r = Requester()
m = Messenger()

class Super:
def __init__(self,a=None,b=None,c=None):
print "Initialisiere",a,b,c

class A(Super):
pass

class C(Super):
pass

# registriere Zähler für Nachricht 'class_created'
c = Cntr_class()
m.register("class_created",c)

# Dekoriere Super-Klasse
def Decorator(obj,*arglist,**argdict):
def request(self,req_name,*arglist,**argdict):
address = self
return r(address,req_name,*arglist,**argdict)

def init(self,*arglist,**argdict):
r.register(self.__class__,"get_cntr",Cntr_class.get_cntr)
m("class_created",self.__class__)
self.sub__init__(*arglist,**argdict)

obj.sub__init__ = obj.__init__
obj.__init__ = init
obj.request = classmethod(request)

Decorator(Super)

# jetzt geht's los
if __name__ == '__main__':

a1 = A(1,2,3)
a2 = A(1,b=2)
a3 = A(1,b=2,c=3)

c1 = C()
c2 = C()

s1 = Super()
s2 = Super()
s3 = Super()
s4 = Super()

print " C:",C.request("get_cntr")
print " A:",A.request("get_cntr")
print "Super:",Super.request("get_cntr")
print
print " c2:",c2.request("get_cntr")
print " a2:",a2.request("get_cntr")
print " s1:",s1.request("get_cntr")