Making functions non override-able

后端 未结 5 1037
我寻月下人不归
我寻月下人不归 2020-12-05 03:05

I know python functions are virtual by default. Let\'s say I have this:

class Foo:
    def __init__(self, args):
        do some stuff
    def goo():
                


        
5条回答
  •  余生分开走
    2020-12-05 03:32

    You can use a metaclass:

    class NonOverridable(type):
        def __new__(self, name, bases, dct):
            if bases and "roo" in dct:
                raise SyntaxError, "Overriding roo is not allowed"
            return type.__new__(self, name, bases, dct)
    
    class foo:
        __metaclass__=NonOverridable
        ...
    

    The metatype's new is called whenever a subclass is created; this will cause an error in the case you present. It will accept a definition of roo only if there are no base classes.

    You can make the approach more fancy by using annotations to declare which methods are final; you then need to inspect all bases and compute all final methods, to see whether any of them is overridden.

    This still doesn't prevent somebody monkey-patching a method into a class after it is defined; you can try to catch these by using a custom dictionary as the classes' dictionary (which might not work in all Python versions, as classes might require the class dictionary to be of the exact dict type).

提交回复
热议问题