17

Given a class with some protected members and a public interface to modify them, when is it generally accepted to access the protected members directly? I have some specific examples in mind:

  1. Unit testing
  2. Internal private methods such as __add__ or __cmp__ accessing other's protected attributes
  3. Recursive data structures (e.g. accessing next._data in a linked list)

I don't want to make these attributes public as I don't want them touched publicly. My syntax IDE syntax highlighting keeps saying that I'm wrong with accessing protected members - who is right here?

EDIT - adding a simple example below:

class Complex:
    def __init__(self, imaginary, base):
        self._imaginary = imaginary
        self._base = base

    def __str__(self):
        return "%fi + %f" % self._base, self._imaginary

    def __add__(self, other):
        return Complex(self._imaginary + other._imaginary, self._base + other._base)

Pycharm highlights other._imaginary and other._base with the following:

Access to a protected member _imaginary of a class

Eli
  • 4,576
  • 1
  • 27
  • 39
Raven
  • 648
  • 1
  • 7
  • 18
  • The three examples you gave are reasonable. Also, it's acceptable to access them (obviously) in the code when needed. Can you post what your syntax highlighter tells you? I'm asking for it because it's pretty basic that protected members are accessed. – nir0s Mar 11 '17 at 14:17

1 Answers1

7

Solved - the problem was actually to do with lack of type-hinting. The below now works:

class Complex:
    def __init__(self, imaginary, base):
        self._imaginary = imaginary
        self._base = base

    def __str__(self):
        return "%fi + %f" % self._base, self._imaginary

    def __add__(self, other):
        """
        :type other: Complex
        :rtype Complex:
        """
        return Complex(self._imaginary + other._imaginary, self._base + other._base)
Eli
  • 4,576
  • 1
  • 27
  • 39
Raven
  • 648
  • 1
  • 7
  • 18
  • Should've been possible writing `(self, other: Complex) -> Complex` in the function signature, but it sadly isn't possible to reference the current class using that syntax, as far as I know... – Andreas is moving to Codidact Jun 27 '19 at 17:24
  • 1
    @Chris This was written for python 2.7 which didn't have type annotation but i don't see why it shouldn't work – Raven Aug 13 '19 at 10:41
  • @Chris FYI https://stackoverflow.com/questions/33533148/how-do-i-specify-that-the-return-type-of-a-method-is-the-same-as-the-class-itsel – Raven Aug 13 '19 at 10:58