When to use Abstract Class in Python?

In this article, I would like to answer a common question that pops up in mind whenever we start to learn Object Oriented Programming in Python.  But before we begin exploring the use case, first lets briefly discuss about what really is an abstract class in python:

abstract_base_class_python

Abstract Class

Abstract Class is a class that contains one or more abstract methods. These abstract methods are  methods without any implementation!

Sounds weird right?  Actually it is true for most of the Object Oriented Programming Language. Abstract method has no implementation in other words no function body! Sub classes implement these abstract methods to fulfill their needs.
But, Python’s abstract method is somewhat different as it is possible to create abstract method with body in python! To know more about python’s abstract class checkout this tutorial 

Now, lets move on to our original question when to use abstract class?

Use of Abstract Class

Abstract class is useful when we want to define many different classes with similar class structure e.g. with same method signatures. Now I will try to explain it with an example. Lets say we want to create classes for different shapes such as Triangle, Rectangle, Pentagon, Hexagon and so on…

In this case, you will find a lot of attributes that are common in each shape but, require different implementation.
For example, consider the attribute area, for all these shapes you will need different formulas to calculate area. Hence, for each classes of Triangle, Rectangle and other shapes there will always be a method called area which will calculate area but, the implementation of this method ‘area’ will vary from one to another.
Like the area attribute there are tons of different attributes that are common in each shape but requires different implementation for each classes. These common properties will be pretty cumbersome to handle if we don’t group them.
Thus, it opens up an opportunity to abstract things little bit so that we can maintain them in a better way.

We can simply create an Abstract class and name it say as `Polygon` with all the common attribute/properties of shapes and, use it to create rest of the classes for different shapes.

from abc import ABC, abstractmethod


class Polygon(ABC):
    @abstractmethod
    def area(self):
        pass
    @abstractmethod
    def perimeter(self):
        pass

The plus point is, abstract class can’t be instantiated. So, object creation by instantiating the Abstract Class Polygon won’t be possible.

If you try to instantiate the Polygon object like below:

obj = Polygon()

It will raise an Exception

TypeError: Can't instantiate abstract class Polygon with abstract methods area

Now that we have our abstract base class for different shapes we can create different sub classes for these shapes just like below:


P.S. Whenever you find a situation where many of your classes has a common structure but require different implementations you can use abstract class to construct a Base Class for abstraction. 

Why Abstract Class is necessary?

Abstract class offer many things such as semantic contract between clients & class implementations, also provides protection from missing implementations of must needed methods of sub classes. It means rather than getting an AttributeError at run time just to know that you forgot to implement something really important, the abstract class will let you know straight at initialization that you have forgotten to implement an important method(abstract)!

By making sure at instantiation time  that the sub classes implement some particular methods while maintaining class hierarchy Python’s Abstract Base class saves you from bugs and overheads.

I would recommend reading this stack overflow question and answers for the in depth discussion on the above question.

 

Privacy Policy

wasi0013.com (“wasi0013.com” or “we”) is dedicated to protecting the privacy rights of our users (“users” or “you”).
This Online Privacy Policy (“Privacy Policy”) has been crafted to inform you as to the ways we collect, store, use, and manage the information you provide in connection with any wasi0013.com game or application (“Service”).
Please note that the scope of this Privacy Policy is limited to only information collected from “wasi0013.com” through use of the Service.
By using the Service, you are agreeing to the collection and use of your personal information as outlined in this Privacy Policy.
We may amend the Privacy Policy from time to time, and we encourage you to consult the Privacy Policy regularly for changes.

Information Collected and Used

Our primary objective in collecting user information is to provide and enhance the Service and to enable users to easily navigate and enjoy the Service.
When you install any of our games or applications, we may collect and record the information you provide us voluntarily in accordance with the policies and terms.
The types of personal information collected in accordance with the activities listed above may vary depending on the activity.
This “personal information” is defined as information about you that can be used to contact or identify you.
Personal information may include:

  • your name
  • user identification number
  • email address.
  • Additionally, we may acquire information from you through
    • your access on the Service
    • your email of a question to our customer support or
    • your purchase of a virtual product of any type.
  • Please note that because a third party site manages the purchases offered by the Service, we do not have access to your credit card details and billing information.
  • “wasi0013.com” may also invite you to share non-personal information about yourself which may include but is not limited to:
    • your age or date of birth
    • your gender
    • information about the hardware you may own
    • your favorite websites
    • friend information and
    • fan pages (collectively referred to as “non-personal information”).
  • If non-personal information is collected for an activity that also requires personal information, “wasi0013.com” may combine your non-personal information with your personal information in an attempt to provide you with a better user experience, to improve the quality and value of the Services and to analyze how our Service is used.
  • The Service may also record game play information such as your high scores or game session duration.
  • In addition to information collected as described above, you may choose to share additional information about yourself throughout the Service, such as in games or on message boards.
  • Any actions you perform with other players are considered public, and are your sole discretion.
  • Finally, any time you access the Service, we may collect aggregate information including but not limited to internet protocol addresses, browser type, browser language, referring / exit pages and URLs, platform type, number of clicks, domain names, landing pages, pages viewed and the order of those pages, the amount of time spent on particular pages, and the date and time of this activity.
  • We use this information to better tailor the Service to your interests, to provide you more efficient customer support, and to overall enhance the Service.
  • In all cases of data access and collection, the information you provide will not be disclosed, rented, leased, loaned, sold, or otherwise voluntarily distributed to unaffiliated third parties and will be used solely for the purpose of providing you with and improving the Service.

Other Disclosure of Your Personal Information

You understand and agree that we may be required to disclose any personal information if required to do so by law or in the good faith belief that such disclosure is reasonably necessary to avoid liability, to comply with legal process, including but not limited to a search warrant, subpoena, statute, or court order, or to protect our rights and property, or that of the public.
Additionally, in the event of a merger, acquisition, reorganization, bankruptcy, or other similar event, customer information may be transferred to the successor or assignee, if permitted by and done in accordance with applicable law.

Links

The Service may contain links to other websites.
The fact that the Service links to a website or presents a banner ad or other type of advertisement does not mean that “wasi0013.com” endorses or authorizes that third party, nor is it a representation of our affiliation with that third party.
“wasi0013.com” is in no way responsible for the privacy policies of these other websites to which you chose to access from the Service.
Please be sure to read the privacy policies of those websites when exiting the Service.

Security

We have put in place reasonable technical and organizational measures designed to secure your personal information from accidental loss and from unauthorized access, use, alteration or disclosure. However, we cannot guarantee that unauthorized third parties will never be able to overcome those measures or use your personal information for improper purposes. Also please note that email and messaging systems are not considered secure, so we discourage you from sending us personal information through these mediums.

Policy Regarding Children

The Service is not geared toward children under the age of 13 and we do not knowingly collect personal information from children under the age of 13. If we learn that a child under 13 has provided us with personal information we will delete such information from our files as quickly as possible.

Contacting Us

If you have any questions about this Privacy Policy, please contact us at wasi0013@gmail.com