我在Python中学习OOP,并遇到了一个问题。如何从对象方法中正确访问受保护的类属性?示例代码:

问题描述 投票:0回答:1
error: Cannot assign to class variable "_foo" via instance [misc]

,让我们尝试一下:
self.__class__._foo
。再次错过!现在拉夫发誓:

SLF001 Private member accessed: `_foo` | 9 | def baz(self, num: int) -> None: 10 | self.__class__._foo = num | ^^^^^^^^^^^^^^^^^^^ SLF001 11 | 12 | if __name__ == "__main__": |
那么正确的方法是什么?
    

问题不是该变量受到保护,而是它是一个

ClassVar
因此,您可以将变量定义为:

_foo: int = 2

python mypy ruff
1个回答
0
投票
ClassVar

@_SpecialForm
def ClassVar(self, parameters):
    """Special type construct to mark class variables.

    An annotation wrapped in ClassVar indicates that a given
    attribute is intended to be used as a class variable and
    should not be set on instances of that class. Usage::

      class Starship:
          stats: ClassVar[Dict[str, int]] = {} # class variable
          damage: int = 10                     # instance variable

    ClassVar accepts only types and cannot be further subscribed.

    Note that ClassVar is not a class itself, and should not
    be used with isinstance() or issubclass().
    """
    item = _type_check(parameters, f'{self} accepts only single type.')
    return _GenericAlias(self, (item,))


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.