Verfasst: Dienstag 2. Juni 2009, 15:51
Achso - Bitte um Entschulding, da hatte ich "methodDictionaries" falsch aufgefasst. Nun, die einfachste Möglichkeit dafür bietet __setattr__ und __delattr__, ich nutze eine Closure:
Wahlweise dann natürlich mit Initialisierung von bereits vorhandenen Methoden. Ob man __dict__ in Metaklassen genauso manipulieren kann, wie __dict__ einer Instanz, weiß ich nicht - naive Versuche scheitern. Aber da man sich Metaklassen selbst zusammenbauen kann wie man will, bin ich zuversichtlich, das es da sicherlich einen Weg gibt (Eventuell über die Metaklasse der Metaklasse
). Manipulationen an __dict__ funktionieren mit __get/set/delattr__ aber doch recht gut (die Möglichkeit hätte ich sowieso vorher in Betracht ziehen sollen).
Code: Alles auswählen
In [5]: def include(into=()):
...: class MetaCls(type):
...: def __setattr__(self, name, value):
...: if isinstance(value, types.FunctionType):
...: for cls in into:
...: setattr(cls, name, value)
...: super(MetaCls, self).__setattr__(name, value)
...: def __delattr__(self, name):
...: if isinstance(getattr(self, name), types.MethodType):
...: for cls in into:
...: delattr(cls, name)
...: super(MetaCls, self).__delattr__(name)
...: return MetaCls
...:
In [7]: import types
In [8]: class A(object):
...: pass
...:
In [9]: class B(object):
...: pass
...:
In [10]: class C(object):
....: __metaclass__ = include((A, B))
....: pass
....:
In [11]: C.a = lambda self: 42
In [12]: print A().a()
42
In [13]: print B().a()
42
In [14]: print C().a()
42
In [15]: del C.a
In [16]: print A().a()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/home/str1442/<ipython console> in <module>()
AttributeError: 'A' object has no attribute 'a'
In [17]: print B().a()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/home/str1442/<ipython console> in <module>()
AttributeError: 'B' object has no attribute 'a'
In [18]: print C().a()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/home/str1442/<ipython console> in <module>()
AttributeError: 'C' object has no attribute 'a'
In [19]: def greet(self):
....: print "Greet from: ", self
....:
....:
In [20]: C.greet = greet
In [21]: A().greet()
Greet from: <__main__.A object at 0x929ff8c>
In [22]: B().greet()
Greet from: <__main__.B object at 0x929ff8c>
In [23]: C().greet()
Greet from: <__main__.C object at 0x95f1c0c>
