python/PyCharm:访问同一类的另一个对象的受保护成员 [英] python / PyCharm: access to a protected member of another object of the same class
问题描述
在我的类 MyHeader
的方法中,我访问另一个 MyHeader
对象 new_header
的私有属性 _label
:
In a method of my class MyHeader
i access the private property _label
of another MyHeader
object new_header
:
class MyHeader:
def __init__(self, label, n_elem):
self._label = label
self._n_elem = n_elem
def check_header_update(self, new_header):
# check that label is preserved
if new_header._label != self._label:
raise Exception("new header must have the same label")
在 PyCharm 中,这会导致语法突出显示错误访问类的受保护成员 _label".
In PyCharm, this results in the syntax highlighting error "Access to a protected member _label of a class".
我尝试指定 new_header
参数的类型:
I tried specifying the type of the new_header
parameter:
def check_header_update(self, new_header: MyHeader):
但这无法识别,并且在运行时会导致错误NameError: name 'MyHeader' is not defined".
but this is not recognized, and at run-time this leads to the error "NameError: name 'MyHeader' is not defined".
知道如何以可接受的方式访问受保护的成员吗?
Any idea how to access the protected member in an accepted way?
推荐答案
键入函数的正确方法是使用 转发引用,然后像这样输入您的check_header_update
.请注意,为了完整起见,我还添加了返回类型:
The correct way to type your function would be to use forward references, and type your check_header_update
like so. Note that I'm also adding the return type, for completeness:
def check_header_update(self, new_header: 'MyHeader') -> None:
类型需要是字符串的原因是因为当你定义check_header_update
时,MyHeader
还没有完全定义,所以不是东西可以参考.
The reason why the type needs to be a string is because when you're defining check_header_update
, MyHeader
hasn't been fully defined yet, so isn't something you can refer to.
但是,我不记得这是否最终会解决问题.如果没有,那么我要么:
However, I don't remember if this will end up fixing the problem or not. If it doesn't, then I would either:
- 通过删除下划线使
_label
成为非私有 - 制作某种getter方法或使用属性让其他人访问数据
- Make
_label
non-private by removing that underscore - Make some kind of getter method or use properties to let other people access that data
这篇关于python/PyCharm:访问同一类的另一个对象的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!