Python-访问类的受保护成员_ [英] Python - Access to a protected member _ of a class
问题描述
给出一个包含一些受保护成员的类,并使用一个公共接口对其进行修改,通常什么时候可以直接访问受保护成员?我想到了一些具体的例子:
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:
- 单元测试
- 内部私有方法(例如__add__或__cmp__)访问其他受保护的属性
- 递归数据结构(例如,访问链表中的next._data)
我不想公开这些属性,因为我不想公开地触摸它们.我的语法IDE语法高亮显示,我一直在错误地访问受保护的成员-谁在这里?
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使用以下内容突出显示 other._imaginary 和 other._base :
Pycharm highlights other._imaginary and other._base with the following:
访问类的受保护成员_imaginary
Access to a protected member _imaginary of a class
推荐答案
已解决-问题实际上与缺乏类型提示有关.现在可以使用以下内容:
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)
这篇关于Python-访问类的受保护成员_的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!