混淆抽象基类中的继承对象

时间:2012-02-27 22:26:23

标签: python

我对ABCs中的继承实例变量感到有点困惑。我写了一个例子来表明我的困惑。 A类需要一个B类继承的列表,但它必须是一个实例对象而不是一个类对象。但是B类也需要自己的实例变量local。谁能让我直截了当?

#!python
from abc import ABCMeta, abstractmethod, abstractproperty
import unittest

class A(object):

    __metaclass__ = ABCMeta
    _internal = ['initialized']

    @property
    def internal(self):
        return self._internal

    def get_a(self):
        return self._internal

    @abstractmethod
    def set_a(self, value):
        pass

class B(A):   
    def __init__(self):
       self.local = 'OK'


    def get_local(self):
        return self.local

    def set_a(self, value):
        self._internal.append(value)


class TestCase(unittest.TestCase):

    def test_implementation(self): 
        self.assertEqual(['initialized'], B().get_a() )  # this passes but for wrong reason
        b_used = B().set_a('used') 
        b_unused = B()

        print "b_used.get_a() should return ['initialized','used']"
        print "b_unused.get_a() should return ['initialized']"
        print "b_used.get_local() should equal b_unused.get_local() = 'OK'"

        self.assertEqual(['initialized'], b_unused.get_a())  # >> fails with ['initialized'] =! ['initialized', 'used']
        self.assertNotEqual(b_unused.get_a(), b_used.get_a())


if __name__ == "__main__":
    unittest.main()

问题是_internal是类A的类obj。我需要它作为B类的实例对象。

提前致谢

2 个答案:

答案 0 :(得分:1)

您应该在__init__()中初始化实例属性,并在__init__()中调用基类B

class A(object):
    __metaclass__ = ABCMeta
    def __init__(self):
        self._internal = ['initialized']
    ...

class B(A):   
    def __init__(self):
        A.__init__(self)
        self.local = 'OK'
    ...

您还应该修复单元测试:

class TestCase(unittest.TestCase):

    def test_implementation(self): 
        self.assertEqual(['initialized'], B().get_a() )  # this passes but for wrong reason
        b_used = B()
        b_used.set_a('used') 
        b_unused = B()
        ...

答案 1 :(得分:0)

应在方法中定义实例属性,例如__init__,方法是在self上设置。