最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Access to protected class attributes from object methods - Stack Overflow

programmeradmin3浏览0评论

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
  • This question is similar to: Class (static) variables and methods. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – MT0 Commented Mar 14 at 10:49
  • Decorate the methods as classmethods fiddle. – MT0 Commented Mar 14 at 10:51
  • @MT0 , no, that's not exactly what I'm looking for. It talks generally about static attributes and methods. I want to understand how to properly address private ones. P.S. I just tried one of the methods specified there, namely type(self)._foo = num, but ruff still curses the same way. – AsfhtgkDavid Commented Mar 14 at 11:04
  • 1 ClassVar 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
  • 1 @Daraan , Yes, I need to change the attribute in all instances – AsfhtgkDavid Commented Mar 14 at 11:12
 |  Show 2 more comments

3 Answers 3

Reset to default 1

To summarize you have a ClassVar and a protected value. ClassVars should be only set on the class object or within classmethods. 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 ClassVars 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())
发布评论

评论列表(0)

  1. 暂无评论