多类继承

时间:2013-12-31 07:37:20

标签: python-2.7

希望C类包含所有已定义的选项和常用函数,然后让A类和B类继承它们。 C类还应通过选项调用返回选定的类main方法。

  1. 这里使用super是正确的吗?
  2. 有更好的替代方法吗?
  3. 我的尝试:

    class A(object):
        def main(self):
            print "A"
            print self.test
            return True
    
    class B(object):
        def main(self):
            print "B"
            print self.test
            return False
    
    class C(A,B):
        def __init__(self, options):
            self.__call = options.get('call')
            self.test = "test"
    
        def main(self):
            if self.__call == 'A':
                return super(C, self).main()
            if self.__call == 'B':
                return super(A, self).main()
    
    if __name__ == '__main__':
        print C({"call": "B"}).main()
        print([cls.__name__ for cls in C.mro()])
    

    A,B的例子,继承自C - @Khalid

    class C(object):
        def __init__(self, options):
            self.__call = options.get('call')
            self.test = "test"
    
    class A(C):
        def __init__(self, opt):
            super(A, self).__init__(opt)
    
        def main(self):
            print "A"
            print self.test
            return True
    
    class B(C):
        def __init__(self, opt):
            super(B, self).__init__(opt)
    
        def main(self):
            print "B"
            print self.test
            return False
    
    if __name__ == '__main__':
        opts = {"call": "B"}
        if opts.get('call') == 'A':
            print A(opts).main()
        if opts.get('call') == 'B':
            print B(opts).main()
        print([cls.__name__ for cls in C.mro()])
    

0 个答案:

没有答案