@abstractmethod in python

Home Forums Python Programming @abstractmethod in python

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #2117 Reply
    Humble
    Keymaster

    Previously I wrote about @staticmethod and @classmethod… One more called @abstractmethod exist in python and useful at times.

    In simple terms @abstractmethod means , the subclasesses ( derived) should implement the method in its class definition and you can not skip it.

    There is a builtin module called “abc” which provides abstractmethod decorator..: abc stands for abstract base class..

    >>>from abc import ABCMeta, abstractmethod  
    or 
    >>> import abc
    >>> dir(abc)
    ['ABCMeta', 'WeakSet', '_C', '_InstanceType', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'abstractmethod', 'abstractproperty', 'types']
    >>> 
    >>> class sports:
    ...     __metaclass__ = ABCMeta
    ...     @abstractmethod
    ...     def football(self):
    ...             print "I am football"
    ... 
    >>> sports()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: Can't instantiate abstract class sports with abstract methods football
    >>> class game(sports):
    ...     def cricket(self):
    ...             print "I am cricket"
    ... 
    >>> g = game()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: Can't instantiate abstract class game with abstract methods football
    
    >>> class game(sports):
    ...     def cricket(self):
    ...             print "I am cricket"
    ...     def football(self):
    ...             super(game,self).football()
    ...     
    ... 
    >>> g = game()
    >>> g = game().football()
    I am football
    >>> 
    
    
    
    As you can see above, the subclass or derived class can not be "initialized" without defining "abstractmethod" (defined in the parent class.) in it. This will make sure all sub classes have these methods defined.
Viewing 1 post (of 1 total)
Reply To: @abstractmethod in python
Your information: