首先,Mixin不是类的继承。传统的,一个类A继承了某个类B,那么A就可以直接调用B中的非private的方法。但是在Mixin中,A与B没有继承关系,而A却能使用B的非private的方法。
其次,Mixin的这些行为是在运行时发生的,而不是静态指定的。
下面是一个来自Python的Mixin的例子:
John 翻著新的一期 LJ(Linux Journal)
[John@mars /tmp]# vi Lover.py
class lover:
def __init__(self,man='man',woman='woman'):
self.lover='When a '+man+' love a '+woman
print self.lover
def smile(self):
print self.lover+':-)'
def kiss(self):
print self.lover+':-)(-:'
[John@mars /tmp]# python
Python 2.1 (#1, Apr 18 2001, 17:55:45)
[GCC 2.95.3 19991030 (prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>>from Lover import lover
>>>John_and_Rose=lover()
When a man love a woman
>>>John_and_Rose.smile()
when a man love a woman:-)
>>>John_and_Rose.kiss()
when a man love a woman:-)(-:
>>>John_and_Rose.sayGoodBye()
Traceback (most recent call last):
File "", line 1, in ?
AttributeError: lover instance has no attribute 'sayGoodBye'
>>>John_and_rose.JohnAskWhy()
Traceback (most recent call last):
File "", line 1, in ?
AttributeError: lover instance has no attribute 'JohnAskWhy'
>>>class RoseLoveSomebodyElse:
def sayGoodBye(self):
print "Let's say goodbye tonight."
>>>lover.__bases__+=(RoseLoveSomebodyElse,)
>>>John_and_Rose.sayGoodBye()
Let's say goodbye tonight.
>>>