mix-ins的简单介绍

最近熟悉satchmo接触到mix-ins,mix-ins 是一种将某个类中的方法混入其他类中的软件开发风格。简单的说,就是一个类可以使用其他类的方法。这个初听起来有点像类的继承,但是这与传统的类继承的方式不一样。
        首先,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.
>>>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值