You can use the Abstract Base Classes to implement abstract methods in Python. For example, if you have an Animal class and a Cat class like the following:
class Animal():
def speak(self):
print("Animal speak")
class Cat(Animal):
pass
class Doc(Animal):
pass
Cat().speak() # returns "Animal speak"
Dog().speak() # returns "Animal speak"
You can turn Animal.speak() to an abstract method with a metaclass and a decorator:
import abc
class Animal(metaclass=abc.ABCMeta):
@abc.abstractmethod
def speak(self):
print("Animal speak")
class Cat(Animal):
def speak(self):
print("Cat speak")
class Dog(Animal):
pass
Cat().speak() # returns "Cat speak"
Dog().speak() # returns "TypeError: Can't instantiate abstract class Dog with abstract methods speak"
Note that although the Animal.speak() method is always shadowed by its subclass method, it can still be called explicitly by using super():
class Cat(Animal):
def speak(self):
super().speak()
Cat().speak() # returns "Animal speak"
No comments:
Post a Comment