Reputation: 99
Is there any way to implement interface functionality in Python 3.x just like in PHP? I would like to declare a method in parent class with no body but I would like to force to override this method in inherited classes.
(In PHP in case you don't override methods declared in interface then you get an error message)
In PHP way (below you get error message because you don't implement getModel() method):
interface Car {
public function setModel($name);
public function getModel();
}
class miniCar implements Car {
private $model;
public function setModel($name)
{
$this -> model = $name;
}
}
Upvotes: 1
Views: 177
Reputation: 5660
Look into the abc
module:
from abc import ABC, abstractmethod
class Car(ABC):
@abstractmethod
def setModel(self, name):
...
@abstractmethod
def getModel(self):
...
Then, if you try to instantiate a class with no methods:
class MiniCar(Car):
pass
x = MiniCar()
You get
TypeError: Can't instantiate abstract class MiniCar with abstract methods getModel, setModel
Upvotes: 2