0

In this example which I get from https://www.askpython.com/python/oops/abstraction-in-python I try to understand what's the uses of abstraction but I get a little bit confused

#if i dont import this it will run yet so what's the point
from abc import ABC, abstractmethod
class Absclass(ABC):
    def print(self,x):
        print("Passed value: ", x)
    
    #even in here if I delete whole this block it don't make any difference
    @abstractmethod
    def task(self):
        print("We are inside Absclass task")
 
class test_class(Absclass):
    def task(self):
        print("We are inside test_class task")
 
class example_class(Absclass):
    def task(self):
        print("We are inside example_class task")
 
test_obj = test_class()
test_obj.task()
test_obj.print(100)
 
example_obj = example_class()
example_obj.task()
example_obj.print(200)

And How Can I access this?

print("We are inside Absclass task"))
EBG
  • 1
  • 1
  • 1
    Does this answer your question? [Is it possible to make abstract classes in Python?](https://stackoverflow.com/questions/13646245/is-it-possible-to-make-abstract-classes-in-python) – Vytas Oct 23 '21 at 17:58
  • 1
    You would see the effect if you tried to instantiate a subclass of `Absclass` that did *not* override `task`. – chepner Oct 23 '21 at 18:00
  • 1
    Try `Absclass()` and see what happens – wjandrea Oct 23 '21 at 18:00
  • docs: [`@abc.abstractmethod`](https://docs.python.org/3/library/abc.html#abc.abstractmethod) – wjandrea Oct 23 '21 at 18:06

1 Answers1

0

You cannot (unless a subclass uses super().task()), because it is an Abstract Class. The whole point of Abstract classes, is to make the class act as a blueprint for other classes.

By defining an abstract base class, you can define a common Application Program Interface(API) for a set of subclasses. This capability is especially useful in situations where a third-party is going to provide implementations, such as with plugins, but can also help you when working in a large team or with a large code-base where keeping all classes in your mind is difficult or not possible.

We are inheriting from the blueprint(Absclass) and using it's functionality. Look at the python documentation: https://docs.python.org/3/library/abc.html

If we run the code, make an instance of the class, and call it's task function, we will get this error.

a = Absclass()
a.task()
TypeError: Can't instantiate abstract class Absclass with abstract methods task
krmogi
  • 2,588
  • 1
  • 10
  • 26
  • 1
    You can, if for example a subclass uses `super().task()` from its own `task` method. Making a method abstract does not make it uncallable; it just makes a (sub)class uninstantiable if it does not override the method with a non-abstract method. – chepner Oct 23 '21 at 18:02