Reputation: 2487
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")
Upvotes: 9
Views: 1778
Reputation: 12401
Side note: In strongly typed languages, a lot of the reason for abstract classes for common interface is to satisfy the typing system, i.e. if you wanted something like
int myfunc(Animal)
and you sent it
int myfunc(Duck)
this would only work if Duck was actually a subclass of Animal, even if the interface was the same; else it would throw a compiler error on the mismatched type.
In python, python doesn't care what the type is, only that the attribute or method you are accessing exists. So a lot of those cases no longer absolutely require a base class. But it's still a good idea IMHO, since you can put on the function 'This expects an Animal', rather than 'This expects one of classes A,B,C' or (worse yet) 'This expects an object that implements x,y,z functions with these signatures'. Easier for you to read later, easier for others to use.
Upvotes: 1
Reputation: 482
If you only have a Duck class and that's the only type of Animal that you'll ever have, it's probably not worth the extra work to have an Animal class. On the other hand, if you're going to have multiple animals and need a common way to interface with all animals without caring which type of animal it is, then yes an abstract class is useful. It really depends on the project you're working on.
Upvotes: 1
Reputation: 21
It depends on what you're trying to do. For example, if you intend to have many other animal classes (Dog, Cat, Fox), and you want to them all to do some standard procedures (for example, run around for a while and then speak their particular sounds), then having an abstract superclass would be useful to avoid repeated code.
Upvotes: 1
Reputation: 500427
If all of the functionality lives in the concrete class -- as is the case in your example -- I don't see any benefit to having the base class.
If, however, some of the functionality can be shared by subclasses (i.e. not all of Animal
's methods are abstract), one could argue that having a common base class would be beneficial. The common functionality could then be placed into the base class and automatically shared by the subclasses.
Upvotes: 4
Reputation: 599630
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.
Upvotes: 5