0

I wanted to define the api in superclass A, and use the data property directly in subclass B, but it is trying to access the __data in A apprently.

I was expecting to see [4, 5] in output

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'
Shuman
  • 3,914
  • 8
  • 42
  • 65
  • Read up on *"name mangling"*, see e.g. https://stackoverflow.com/q/1301346/3001761. There's no need for the double underscore here. – jonrsharpe Mar 25 '20 at 23:01
  • @jonrsharpe I wanted to protect the instance variable, that's why the __ – Shuman Mar 25 '20 at 23:04
  • 1
    Then use a *single* leading underscore, but note that neither actually protects it except by convention. – jonrsharpe Mar 25 '20 at 23:05

1 Answers1

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]
Rusty Widebottom
  • 985
  • 2
  • 5
  • 14