Home › Forums › Python Programming › @abstractmethod in python
- This topic has 0 replies, 1 voice, and was last updated 10 years, 4 months ago by Humble.
Viewing 1 post (of 1 total)
-
AuthorPosts
-
HumbleKeymaster
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.
-
AuthorPosts
Viewing 1 post (of 1 total)