[Level 2] Python abstract method testing
#!/bin/env python import os, sys from abc import * # ================================================= class ToolCmd(object): __metaclass__ = ABCMeta def __init__(self): pass @abstractmethod def doLocalAction(self): pass class DoAction(ToolCmd): def __init__(self): pass def doLocalAction(self): print 'doLocalAction()' # ================================================= class Test1(DoAction, ToolCmd): def __init__(self): pass class Test2(ToolCmd): def __init__(self): pass #class Test3(ToolCmd, DoAction): # def __init__(self): # pass # ================================================= t1 = Test1() t1.doLocalAction() t2 = Test2() t2.doLocalAction() #t3 = Test3() #t3.doLocalAction() # =================================================
Test Run: (Run-time error) $ ./c.py doLocalAction() Traceback (most recent call last): File "./c.py", line 42, int2 = Test2() TypeError: Can't instantiate abstract class Test2 with abstract methods doLocalAction $
#!/bin/env python import os, sys from abc import * # ================================================= class ToolCmd(object): __metaclass__ = ABCMeta def __init__(self): pass @abstractmethod def doLocalAction(self): pass class DoAction(ToolCmd): def __init__(self): pass def doLocalAction(self): print 'doLocalAction()' # ================================================= class Test1(DoAction, ToolCmd): def __init__(self): pass class Test2(ToolCmd): def __init__(self): pass class Test3(ToolCmd, DoAction): def __init__(self): pass # ================================================= t1 = Test1() t1.doLocalAction() t2 = Test2() t2.doLocalAction() t3 = Test3() t3.doLocalAction() # =================================================
Test Run: (Compiler-time error) $ ./c.py Traceback (most recent call last): File "./c.py", line 33, inclass Test3(ToolCmd, DoAction): File "/usr/lib/python2.6/abc.py", line 79, in __new__ cls = super(ABCMeta, mcls).__new__(mcls, name, bases, namespace) TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution order (MRO) for bases ToolCmd, DoAction stanley@Stanley-Ubuntu:/tmp$ $
Wish this helps.
regards,
Stanley Huang
Comments
Post a Comment