Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

python - Making functions non override-able

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():
        print "You can overload me"
    def roo():
        print "You cannot overload me"

I don't want them to be able to do this:

class Aoo(Foo):
    def roo():
        print "I don't want you to be able to do this"

Is there a way to prevent users from overloading roo()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...