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
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,))