Issue
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")
In PyCharm, this results in the syntax highlighting error "Access to a protected member _label of a class".
I tried specifying the type of the new_header
parameter:
def check_header_update(self, new_header: MyHeader):
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?
Solution
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:
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:
- Make
_label
non-private by removing that underscore - Make some kind of getter method or use properties to let other people access that data
Answered By - Michael0x2a
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.