python / PyCharm: access to a protected member of another object of the same class

99封情书 提交于 2019-12-11 04:44:21

问题


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:

  1. Make _label non-private by removing that underscore
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!