Created
November 13, 2017 06:08
-
-
Save suncle1993/04ebc90cd4f3772b302d5becb6e70b9a to your computer and use it in GitHub Desktop.
Python MixIn的使用
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Base(object): | |
"""Base class for mixer classes. All mixin classes | |
require the classes they are mixed in with to be | |
instances of this class (or a subclass).""" | |
def __init__(self,b): | |
self.b = b # Mixin classes assume this attribute will be present | |
class MixinBPlusOne(object): | |
"""A mixin class that implements the print_b_plus_one | |
method.""" | |
def __init__(self): | |
print 'MixinBPlusOne initialising' | |
def print_b_plus_one(self): | |
print self.b+1 | |
class MixinBMinusOne(object): | |
"""A mixin class that implements the print_b_minus_one | |
method.""" | |
def __init__(self): | |
print 'MixinBMinusOne initialising' | |
def print_b_minus_one(self): | |
print self.b-1 | |
class Mixer(Base,MixinBPlusOne,MixinBMinusOne): | |
"""A mixer class (class that inherits some mixins), this | |
will work because it also inherits Base, which the | |
mixins expect.""" | |
def __init__(self,b): | |
# I feel like I should be using super here because | |
# I'm using new-style classes and multiple | |
# inheritance, but the argument list of | |
# Base.__init__ differs from those of the Mixin | |
# classes, and this seems to work anyway. | |
Base.__init__(self,b) | |
MixinBPlusOne.__init__(self) | |
MixinBMinusOne.__init__(self) | |
class BrokenMixer(MixinBPlusOne,MixinBMinusOne): | |
"""This will not work because it does not inherit Base, | |
which the mixins expect it to do.""" | |
pass | |
m = Mixer(9) | |
m.print_b_plus_one() | |
m.print_b_minus_one() | |
# m = BrokenMixer(9) | |
# m.print_b_plus_one() # It'll crash here. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment