I'm trying to find the python equivalent of c++ const methods. That is,
methods that are forbidden to change any data member of their class.
from typing import Final
age: Final = 2
age += 3 # <----- warn about this -- works!
class Person:
def __init__(self, age: int) -> None:
self.age = age
def happy_birthday(self: Final[Person]) -> None:
self.age += 1 # <----- warn about this -- how?
I've never seen type hints used with self so it looks a bit weird (and doesn't work)
main.py:4: error: Cannot assign to final name "age"
main.py: note: In member "happy_birthday" of class "Person":
main.py:9: error: Final can be only used as an outermost qualifier in a variable annotation [misc]
def happy_birthday(self: Final[Person]) -> None:
^
Is there any other way to achieve this? Note that the attributes should still allow modification in other methods.