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>
