Making functions non override-able

后端 未结 5 1028
我寻月下人不归
我寻月下人不归 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:46

    Late to the party but not all python methods are "virtual" by default - consider:

    class B(object):
        def __priv(self): print '__priv:', repr(self)
    
        def call_private(self):
            print self.__class__.__name__
            self.__priv()
    
    class E(B):
        def __priv(self): super(E, self).__priv()
    
        def call_my_private(self):
            print self.__class__.__name__
            self.__priv()
    
    B().call_private()
    E().call_private()
    E().call_my_private()
    

    Blows due to name mangling:

    B
    __priv: <__main__.B object at 0x02050670>
    E
    __priv: <__main__.E object at 0x02050670>
    E
    Traceback (most recent call last):
      File "C:/Users/MrD/.PyCharm2016.3/config/scratches/test_double__underscore", line 35, in 
        E().call_my_private()
      File "C:/Users/MrD/.PyCharm2016.3/config/scratches/test_double__underscore", line 31, in call_my_private
        self.__priv()
      File "C:/Users/MrD/.PyCharm2016.3/config/scratches/test_double__underscore", line 27, in __priv
        def __priv(self): super(E, self).__priv()
    AttributeError: 'super' object has no attribute '_E__priv'
    

    So if you want to get some help from the language to prohibit people from overriding a bit of functionality that you need inside your class this is the way to go. If the method you want to make final is part of your class API however you are stuck with the comments approach (or metaclass hacks). My personal opinion is that a final keyword is very useful for inheritance - as you can avoid the class breaking in insidious ways when overridden (consider using the "final" method in super implementation for instance and then someone overrides - boom, super broken) - and for documentation purposes (no docs are better than a compile time syntax error) - but Python's dynamic nature would not allow it and hacks are fragile - so add a docstring:

    """DON'T OVERRIDE THIS METHOD"""
    

提交回复
热议问题