如何在 super class 中定义 属性 但在 subclass 中访问它的值?
How to define property in super class but access its value in subclass?
我想在超类 A
中定义 api,并在子类 B
中直接使用 data
属性,但它正在尝试访问 A
中的 __data
apprently。
我期待在输出中看到 [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'
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]
我想在超类 A
中定义 api,并在子类 B
中直接使用 data
属性,但它正在尝试访问 A
中的 __data
apprently。
我期待在输出中看到 [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'
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]