Python - Access to a protected member _ of a class

守給你的承諾、 提交于 2019-12-08 20:09:54

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/42736044/python-access-to-a-protected-member-of-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!