Preventing and enforcing the override in derived classes in Python

In Python, there is nothing like data hiding. However, we can have representation of data hiding with _(single Underscore).

__(Double Underscore) Means the methods and properties can't be overridden in derived classes. Trying to do show causes exceptions.

@abstractmethod  Decorator on any methods mean, that should be overridden for sure in derived class. Not implementing that method causes exceptions.

__xyz__ (Double Underscore prefix and suffix) Means the method/attribute is an builtin, can be overridden. 

Example: 

from abc import ABC, abstractmethod

class Base(ABC):
      def __init__(self):
        
         self.result = self._private()

      def _private(self):
        return "Yes"

      @abstractmethod
      def you_should_override(self):
            pass

    def __you_cant_override(self):
            pass


class Derived(Base):
         def you_should_override(self):
            pass
                

MyObj = Derived()
MyObj. _private   --> Don't do it, it means the private
MyObj. _you_cant_override --> You can neither be accessed nor overridden. 
Rather, it can be accessed by   MyObj. _Test__you_cant_override ; Remember the _Test prefix. 

Comments