17.12.2012 Views

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

506<br />

Techniques avancées<br />

QUATRIÈME PARTIE<br />

Chaque visiteur dispose en entrée de la fonction __call__() l’objet visité, qu’il peut<br />

manipuler à sa guise. La classe visitée fournit quant à elle une méthode accept()<br />

pouvant être appelée par tout visiteur.<br />

Cette mécanique appelant-appelé permet de mettre en place des algorithmes récursifs<br />

basés sur des objets organisés en structure.<br />

L’exemple le plus typique est le parcours d’arbres par le biais d’objets nœuds.<br />

Dans l’exemple ci-dessous, le visiteur Tick parcourt une structure de nœuds pour<br />

déclencher les méthodes tick() de chaque nœud.<br />

Visitor sur MaClasse<br />

ifnot isinstance(visitor, Visitor):<br />

raise TypeError("%s n’est pas un Visitor" % visitor)<br />

visitor(self)<br />

class Node(Visited):<br />

def __init__(self):<br />

self.childs = []<br />

def tick(self):<br />

print('tick at %d' % id(self))<br />

class Tick(Visitor):<br />

def __call__(self, visited):<br />

visited.tick()<br />

for child in visited.childs:<br />

child.accept(self)<br />

root = Node()<br />

for i in range(2):<br />

node = Node()<br />

for y in range(4):<br />

node.childs.append(Node())<br />

root.childs.append(node)<br />

ticker = Tick()<br />

ticker(root)<br />

[..]<br />

[tziade@Tarek Desktop]$ python visitor.py<br />

tick at -1211997076<br />

tick at -1211995892<br />

tick at -1211995828

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!