Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use abstract classes?

Tags:

python

oop

I have read that this is the best way to implement an abstract class in Python (as opposed to the abc module):

class Animal(object):
    def speak(self):
        raise NotImplementedError()

class Duck(Animal):
    def speak(self):
        print("quack")

class Cat(Animal):
    def speak(self):
        print("meow")

However, should I use abstract classes? Should I or should I not just use one less class like so:

class Duck(object):
    def speak(self):
        print("quack")

class Cat(Animal):
    def speak(self):
        print("meow")
like image 734
LazySloth13 Avatar asked Oct 11 '13 14:10

LazySloth13


People also ask

Should I use abstract classes or interfaces?

Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing a common functionality to unrelated classes. Interfaces are a good choice when we think that the API will not change for a while.

What is the benefit of using abstract class?

Abstract classes can be used to store methods in an OOP-based "library"; since the class doesn't need to be instantiated, and would make little sense for it to be, keeping common static methods inside of an abstract class is a common practice.

Is an important use of abstract classes in C++?

Abstract classes are used to express broad concepts from which more concrete classes can be derived. An abstract class type object cannot be created. To abstract class types, however, you can use pointers and references. Declare at least one pure virtual member feature when creating an abstract class.


1 Answers

There's no one answer to this problem. Do you need a consistent interface between types of Animal? Then some kind of abstract base class would be useful, whether it's from abc or not. If Duck is the only Animal, or there are few similarities between them, then there's rarely much point.

like image 182
Daniel Roseman Avatar answered Oct 19 '22 16:10

Daniel Roseman