admin管理员组文章数量:1389981
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?
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?
Share Improve this question edited Mar 14 at 17:18 InSync 11.1k4 gold badges18 silver badges56 bronze badges asked Mar 14 at 10:28 AsfhtgkDavidAsfhtgkDavid 599 bronze badges 7 | Show 2 more comments3 Answers
Reset to default 1To summarize you have a ClassVar
and a protected
value. ClassVar
s should be only set on the class object or within classmethod
s. Protected values should also only be accessed within the class, the clean solution is to use a classmethod to set the ClassVar
:
class Example:
_foo: ClassVar[int] = 2
def bar(self) -> int:
return self._foo # will return self.__class__._foo is not found on instance.
def baz(self, num: int) -> None:
self.class_set_foo(num)
@classmethod
def class_set_foo(cls, value):
# Choose one, depending on wanted subclass behavior:
cls._foo = value # wrt. to current (sub)class, but not parent/sibling classes
# OR
Example._foo = value # for all subclasses
The problem is not that the variable is protected, but that it is a ClassVar
.
So you can define the variable as: _foo: int = 2
According to the documentation in typing.py (also as suggested by mypy) you shouldn't set ClassVar
s from an instance:
@_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,))
If it is a ClassVar
then use a classmethod
to set the value on the class:
from typing import ClassVar
class Example:
_foo: ClassVar[int] = 2
@classmethod
def bar(cls) -> int:
return cls._foo
@classmethod
def baz(cls, num: int) -> None:
cls._foo = num
if __name__ == "__main__":
example1 = Example()
example2 = Example()
Example.baz(1)
print(example1.bar())
fiddle
I cant decorate the methods as classmethods fiddle, because in my project this method uses object attributes, too
Then refer directly to the class in the method (and not to an instance of the class when setting the class variable):
from typing import ClassVar
class Example:
_foo: ClassVar[int] = 2
value: int
def bar(self) -> int:
return Example._foo
def baz(self, num: int) -> None:
Example._foo = num
self.value = num
if __name__ == "__main__":
example1 = Example()
example2 = Example()
example1.baz(1)
print(example1.bar())
本文标签: pythonAccess to protected class attributes from object methodsStack Overflow
版权声明:本文标题:python - Access to protected class attributes from object methods - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744662122a2618307.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
classmethod
s fiddle. – MT0 Commented Mar 14 at 10:51type(self)._foo = num
, but ruff still curses the same way. – AsfhtgkDavid Commented Mar 14 at 11:04ClassVar
means it's value is shared for all instances and subclasses, and should not be set to an individual value for an instance. Is that what you want? – Daraan Commented Mar 14 at 11:08