0

For example, this abstract class:

from abc import ABC, abstractmethod 

class Polygon(ABC): 

    # abstract method 
    def noofsides(self): 
        print("something")

class Triangle(Polygon): 

    # overriding abstract method 
    def noofsides(self): 
        print("I have 3 sides")

...could be written as a superclass and it would do the exact same thing:

class Polygon: 
    def noofsides(self): 
        print("something")

class Triangle(Polygon):
    # overriding abstract method 
    def noofsides(self): 
        print("I have 3 sides")

So I don't see the point in using an abstract class. Can someone explain me please?

  • 2
    Using `ABC` you can add the `@abstractmethod` decorator to a method which will **force** sub-classes to override these methods. Using regular classes there is no such enforcement. If you know Java, this resembles the concept of `Interface`s. Where you declare **which** methods should be present and what are their signatures, and the sub-classes must implement them accordingly – Tomerikoo Mar 01 '20 at 15:34
  • related: [Why use Abstract Base Classes in Python?](https://stackoverflow.com/questions/3570796/why-use-abstract-base-classes-in-python) .. many more with a search similar to `python abstract class site:stackoverflow.com` – wwii Mar 01 '20 at 15:41
  • This can be useful for example in your case, if you want to make sure that each `Polygon` will print a useful message. You can still implement it at the abstract class and call it using `super()`, but this way you make sure the user knows what he's doing. If he doesn't implement it, it will raise an error. He can still call the parent method, but has to do it **knowingly** – Tomerikoo Mar 01 '20 at 15:44

0 Answers0