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

2024-05-17 12:59:39 发布

您现在位置: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的实例对象

提前谢谢


Tags: 对象实例selfgetreturnunusedvaluelocal
2条回答

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

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

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

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

您还应该修复单元测试:

^{pr2}$

相关问题 更多 >