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

前端 未结 4 1235
走了就别回头了
走了就别回头了 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:22

    You can simulate the same effect from Python 3.x quite easily:

    class Final(type):
        def __new__(cls, name, bases, classdict):
            for b in bases:
                if isinstance(b, Final):
                    raise TypeError("type '{0}' is not an acceptable base type".format(b.__name__))
            return type.__new__(cls, name, bases, dict(classdict))
    
    class C(metaclass=Final): pass
    
    class D(C): pass
    

    will give the following output:

    Traceback (most recent call last):
      File "C:\Temp\final.py", line 10, in 
        class D(C): pass
      File "C:\Temp\final.py", line 5, in __new__
        raise TypeError("type '{0}' is not an acceptable base type".format(b.__name__))
    TypeError: type 'C' is not an acceptable base type
    

提交回复
热议问题