`final` keyword equivalent for variables in Python?

后端 未结 11 1979
忘了有多久
忘了有多久 2021-01-30 20:17

I couldn\'t find documentation on an equivalent of Java\'s final in Python, is there such a thing?

I\'m creating a snapshot of an object (used for restorati

11条回答
  •  春和景丽
    2021-01-30 20:47

    Python 3.8 (via PEP 591) adds Final variables, functions, methods and classes. Here are some ways to use it:

    @final Decorator (classes, methods)

    from typing import final
    
    @final
    class Base:
        # Cannot inherit from Base
    
    class Base:
        @final
        def foo(self):
            # Cannot override foo in subclass
    

    Final annotation

    from typing import Final
    
    PI: Final[float] = 3.14159     # Cannot set PI to another value
    KM_IN_MILES: Final = 0.621371  # Type annotation is optional
    
    class Foo:
        def __init__(self):
            self.bar: Final = "baz"   # Final instance attributes only allowed in __init__
    

    Please note that like other typing hints, these do not prevent you from overriding the types, but they do help linters or IDEs warn you about incorrect type usage.

提交回复
热议问题