官术网_书友最值得收藏!

Abstract classes

There are many occasions in which we may want to have partial implementation of a class such that the class defines its objective with a template and it also defines how it must obtain a portion of its objective with the help of a few implemented methods. The remaining portion of the class objective can be left out to be implemented by the subclass, which is mandatory. To implement use cases such as this, we make use of abstract classes. An abstract base class, popularly known as an abc class, is a class that contains abstract methods. An abstract method is a method that does not have an implementation. It simply contains the deceleration and is meant to be implemented in the class that would implement or inherit from the abstract class.

A few important pointers about abstract classes include the following:

  • An abstract method in Python is declared with the @abstractmethod decorator.
  • While an abstract class can contain abstract methods, nothing prevents an abstract class from having normal or non-abstract methods as well.
  • An abstract class cannot be instantiated.
  • The subclass of the abstract class must implement all the abstract methods of the base class. Failing this, it can't be instantiated.
  • If the subclass of an abstract class doesn't implement the abstract methods, it automatically becomes an abstract class, which can be then further extended by another class.
  • Abstract classes in Python are implemented using the abc module.

Let's create a class called Abstract.py and take a look at how abstract classes can be used in Python:

In the preceding example, we created an abstract class called QueueAbs that inherits from the Abstract base class, called ABC. The class has got two abstract methods, enqueue and dequeue, and also one concrete method called printItems(). Then, we created a class called Queue that is a subclass of the QueueAbs abstract base class and that implements the enqueue and dequeue methods. Finally, we make the instance of the Queue class and invoke the methods, as shown previously.

One thing worth remembering here is that in Java and C#, an abstract class can't implement the abstract method. This is not the case with Python. In Python, an abstract method may or may not have a default implementation, but this does not prevent the subclass from overriding it. Irrespective of whether the abstract class method has an implementation or not, it is mandatory for the subclass to override it. 
主站蜘蛛池模板: 洛阳市| 化隆| 瑞丽市| 奉贤区| 犍为县| 富民县| 乌兰察布市| 甘洛县| 莲花县| 绥芬河市| 宜兴市| 沁源县| 宿松县| 宁陵县| 巴林右旗| 老河口市| 苍溪县| 莒南县| 聂拉木县| 徐州市| 阿荣旗| 北票市| 新河县| 新竹县| 郴州市| 鹤山市| 永川市| 兴化市| 广灵县| 彩票| 深泽县| 原平市| 潮安县| 青铜峡市| 定西市| 安岳县| 郁南县| 玉田县| 乐东| 乃东县| 沙坪坝区|