问题
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?
回答1:
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
回答2:
There isn't anything wrong about your initial code sample. It's just that PyCharm doesn't try to guess your parameter type. Most code bases I work with have several thousands warning and even errors from IDE analyses. You can't fix them all.
Anyway, you can specify the type of the parameter through the method docstring and PyCharm won't shout the warning anymore:
class MyHeader:
def __init__(self, label, n_elem):
self._label = label
self._n_elem = n_elem
def check_header_update(self, new_header):
"""
:type new_header: MyHeader
"""
if new_header._label != self._label:
raise Exception("new header must have the same label")
Note that is also work with union types (ex.: str | MyHeader
).
来源:https://stackoverflow.com/questions/44658367/python-pycharm-access-to-a-protected-member-of-another-object-of-the-same-cla