1

What does the abstractmethod decorator in python does?

from abc import abstractmethod class Animal(object): @abstractmethod def walk(self): ''' data ''' pass @abstractmethod def talk(self): ''' data ''' pass class Duck(Animal): name = '' def __init__(self, name): print('duck created.') self.name = name def walk(self): print('walks') def talk(self): print('quack') obj = Duck('duck1') obj.talk() obj.walk() 

But if I comment the decorator, the code still works.

from abc import abstractmethod class Animal(object): def walk(self): ''' data ''' pass def talk(self): ''' data ''' pass class Duck(Animal): name = '' def __init__(self, name): print('duck created.') self.name = name def walk(self): print('walks') def talk(self): print('quack') obj = Duck('duck1') obj.talk() obj.walk() 

My question is why bother to use this decorator? I even delete some of the methods in Duck, say talk. Then it does not crash. I makes me not understand when do we need to use this abstractmethod?

1

1 Answer 1

1

What does the abstractmethod decorator in python does?

What about checking the doc ?

A decorator indicating abstract methods.

Using this decorator requires that the class’s metaclass is ABCMeta or is derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden.

Note that in your example the base Animal class doesn't use ABCMeta as it's metaclass so the decorator is mostly useless indeed.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.