Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 554
Thomas Avatar asked Sep 13 '25 20:09

Thomas


1 Answers

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
like image 172
Michael0x2a Avatar answered Sep 16 '25 11:09

Michael0x2a