如何在超类中定义属性,但在子类中访问其值?

问题描述 投票:0回答:1

我想在超类A中定义api,并直接在子类data中使用B属性,但是它试图适当地访问__data中的A

我原本希望在输出中看到[4, 5]

class A(object):
    def __init__(self):
        self.__data = [1, 2, 3]

    @property
    def data(self):
        return self.__data  


class B(A):
    def __init__(self):
        self.__data = [4,5]


b = B()
print b.data
# AttributeError: 'B' object has no attribute '_A__data'
python subclass
1个回答
1
投票
class A(object):
    def __init__(self):
        self._data = [1, 2, 3]

    @property
    def data(self):
        return self._data  

    @data.setter
    def data(self, value):
        self._data = value

class B(A):
    def __init__(self):
        super(B, self).__init__()
        self.data = [4, 5]

b = B()
print(b.data)

# [4, 5]
© www.soinside.com 2019 - 2024. All rights reserved.