Created
March 14, 2012 02:13
-
-
Save shomah4a/2033432 to your computer and use it in GitHub Desktop.
多重継承を制限してみる in Python
This file contains 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
#-*- coding:utf-8 -*- | |
u''' | |
多重継承を制限するクラスを作って、そのクラスから導出されたクラスが多重継承していたらエラーを吐くメタクラス | |
''' | |
class MultipleInheritanceLimitedError(TypeError): | |
pass | |
def get_limitation_class(cls): | |
u''' 制限が掛けられているであろうクラスを取ってくる ''' | |
for base in cls.__bases__: | |
if isinstance(base, MultipleInheritanceLimitation): | |
return cls | |
result = get_limitation_class(base) | |
if result is not None: | |
return retult | |
def check_multipleinherit(cls): | |
u''' 多重継承を蹴っちゃう ''' | |
bases = cls.__bases__ | |
if len(bases) > 1: | |
msg = '''class {0} was inherits from {1}.''' | |
msg = msg.format(cls.__name__, | |
tuple([x.__name__ for x in bases])) | |
msg2 = ''' Multiple inheritance limited at {0}.'''.format(get_limitation_class(cls).__name__) | |
raise MultipleInheritanceLimitedError(msg+msg2) | |
class MultipleInheritanceLimitation(type): | |
u''' 多重継承を制限するメタクラス ''' | |
def __init__(cls, *args, **argd): | |
super(MultipleInheritanceLimitation, cls).__init__(*args, **argd) | |
check_multipleinherit(cls) | |
if __name__ == '__main__': | |
class Sample(object): | |
u''' メタクラスで制限を掛ける ''' | |
__metaclass__ = MultipleInheritanceLimitation | |
class Base(object): | |
pass | |
class Test(Sample): | |
u''' 単一継承なら問題ない ''' | |
class Test2(Base, Test): | |
u''' 多重継承するとあぼーん ''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment