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")
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With