Final classes in Python 3.x- something Guido isn't telling me?

前端 未结 4 1212
走了就别回头了
走了就别回头了 2020-12-08 13:55

This question is built on top of many assumptions. If one assumption is wrong, then the whole thing falls over. I\'m still relatively new to Python and have just entered the

4条回答
  •  时光说笑
    2020-12-08 14:30

    In Python 3.6, you should block subclassing without using a metaclass like this:

    class SomeBase:
    
        def __init_subclass__(cls, **kwargs):
            super().__init_subclass__(**kwargs)
            if cls is not SomeBase:
                raise TypeError("SomeBase does not support polymorphism.  Use composition over inheritance.")
    
    
    class Derived(SomeBase):
        pass
    

    In Python 3.8, you should also use the final decorator to induce type-checking errors:

    from typing import final
    
    
    @final
    class SomeBase:
        ...
    

    Type-checking is done by programs like MyPy, which are optional.

提交回复
热议问题