Rav*_*ven 7 python oop attributes protected
给定一个具有一些受保护成员的类,并通过一个公共接口对其进行修改,通常什么时候可以直接访问受保护成员?我想到了一些具体的例子:
我不想公开这些属性,因为我不想公开地触摸它们。我的语法IDE语法高亮显示,我在访问受保护的成员时错了-谁在这里?
编辑 -在下面添加一个简单的示例:
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)
Run Code Online (Sandbox Code Playgroud)
Pycharm 使用以下内容突出显示other._imaginary和other._base:
访问类的受保护成员_imaginary
已解决 - 问题实际上与缺乏类型提示有关。以下现在有效:
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)
Run Code Online (Sandbox Code Playgroud)