[Python] Access to protected class attributes from object methods

Discussão em 'Python' iniciado por Stack, Março 14, 2025.

  1. Stack

    Stack Membro Participativo

    I'm learning OOP in python and ran into a problem. How to correctly access protected class attributes from object methods? Example code:

    from typing import ClassVar


    class Example:
    _foo: ClassVar[int] = 2
    def bar(self) -> int:
    return self._foo

    def baz(self, num: int) -> None:
    self._foo = num

    if __name__ == "__main__":
    example1 = Example()
    example2 = Example()
    example1.baz(1)
    print(example1.bar())


    But mypy says:

    error: Cannot assign to class variable "_foo" via instance [misc]


    Ok, let's try this: self.__class__._foo. And misses again! Now ruff is swearing:

    SLF001 Private member accessed: `_foo`
    |
    9 | def baz(self, num: int) -> None:
    10 | self.__class__._foo = num
    | ^^^^^^^^^^^^^^^^^^^ SLF001
    11 |
    12 | if __name__ == "__main__":
    |


    So what's the right way?

    Continue reading...

Compartilhe esta Página