Making the __init__ an abstract method:

from abc import ABCMeta, abstractmethod

class A(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def __init__(self, n):
        self.n = n


if __name__ == '__main__':
    a = A(3)

helps:

TypeError: Can't instantiate abstract class A with abstract methods __init__

Python 3 version:

from abc import ABCMeta, abstractmethod

class A(object, metaclass=ABCMeta):

    @abstractmethod
    def __init__(self, n):
        self.n = n


if __name__ == '__main__':
    a = A(3)

Works as well:

TypeError: Can't instantiate abstract class A with abstract methods __init__
Answer from Mike Müller on Stack Overflow
🌐
Python
docs.python.org › 3 › library › abc.html
abc — Abstract Base Classes
This module provides the infrastructure for defining abstract base classes (ABCs) in Python, as outlined in PEP 3119; see the PEP for why this was added to Python.
Discussions

abstract class, how to create it properly?
create an abstract base class with two int attributes That's not really possible in python. An abstract class must have at least one method decorated with @abc.abstractmethod. You can't make an abstract class with just 2 attributes. You should ask your professor to clarify what they want you to do. More on reddit.com
🌐 r/learnpython
4
2
March 24, 2024
Python Abstract Method With It's own __init__ function - Stack Overflow
How can I define a __init__ function in both the base and derived abstract classes and have all self.* be available in the abstract method? For example: What is the proper way of utilizing functions that are imported in the base class of an abstract class? For example: in base.py I have the following: import abc ... More on stackoverflow.com
🌐 stackoverflow.com
Adding @abstractmethod __init__ to ABC breaks staticmethods
I was trying to create an ABC that also worked as a factory. from abc import ( ABCMeta, abstractmethod, ) class WidgetWithInit(object): __metaclass__ = ABCMeta @abstractmethod def __init__(self, fo... More on github.com
🌐 github.com
5
June 14, 2016
__init__ in ABC abstract class in Python - Stack Overflow
In the below example, do I need to call the super().__init__() from the MySQLdatabase class or it is not needed? If I override the __init__ in the MySQLdatabase then it is my understanding that the More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python.org
discuss.python.org › typing
Enforcing __init__ signature when implementing it as an abstractmethod - Typing - Discussions on Python.org
December 29, 2024 - Hello. I noticed that Pyright doesn’t check the signatures of abstractmethod implementations when the abstractmethod is __init__(). Here’s an example: from abc import ABC, abstractmethod class AbstractA(ABC): @abstractmethod def __init__(self, x: int, y: int): pass @abstractmethod def do_something(self, z: int, u: int): pass class RealA(AbstractA): def __init__(self, x: int): ## No static type checker error self.x = x def do_something...
🌐
Python Course
python-course.eu › oop › the-abc-of-abstract-base-classes.php
20. The 'ABC' of Abstract Base Classes | OOP | python-course.eu
from abc import ABC, abstractmethod class AbstractClassExample(ABC): def __init__(self, value): self.value = value super().__init__() @abstractmethod def do_something(self): pass
🌐
Medium
medium.com › @mhesty71 › what-i-wish-i-knew-about-init-self-super-and-abstract-classes-7103c8b91128
What I Wish I Knew About __init__, self, super(), and Abstract Classes | by maria siagian | Medium
December 17, 2024 - When I started learning Object-Oriented Programming (OOP) in Python, these concepts — __init__, self, super(), and Abstract Base Classes (ABC)—felt like a puzzle. What exactly does __init__ do? What does self actually represent? What’s the point of super()?
🌐
DEV Community
dev.to › sarahs › abstract-classes-in-python-55mj
Abstract Classes in Python - DEV Community
December 20, 2023 - I've been working a lot in C# for school lately, but I was previously learning Python over the summer, so I will do this challenge in Python3 as a refresher. ... Title:, a space, and then the current instance's title. Author:, a space, and then the current instance's author. Price:, a space, and then the current instance's price. ... from abc import ABCMeta, abstractmethod class Book(object, metaclass=ABCMeta): def __init__(self,title,author): self.title=title self.author=author @abstractmethod def display(): pass #Write MyBook class title=input() author=input() price=int(input()) new_novel=MyBook(title,author,price) new_novel.display()
🌐
MakeUseOf
makeuseof.com › home › programming › abstract classes in python: a beginner's guide
Abstract Classes in Python: A Beginner's Guide
September 11, 2021 - At this point, it would be good to mention that—unlike Java—abstract methods in Python can have an implementation.. This implementation can be accessed in the overriding method using the super() method. import abc class AbstractClass(ABC): def __init__(self, value): self.value = value super().__init__() @abc.abstractmethod def some_action(self): print("This is the parent implementation.") class MySubclass(AbstractClassExample): def some_action(self): super().some_action() print("This is the subclass implementation.
🌐
Reddit
reddit.com › r/learnpython › abstract class, how to create it properly?
r/learnpython on Reddit: abstract class, how to create it properly?
March 24, 2024 -

I thought I understood what abstract class means but my professor just commented that it wasn't a abstract class. What I did is essentially this:

first instruction: create an abstract base class with two int attributes then derived another class called Hero with a string attribute which stores the title "hero"

from abc import ABC

class Person(ABC):
def __init__(self, height, speed):
self.height = height
self.speed = speed

def walk(self):
//walk method

from person import Person

class Hero(Person):
def __init__(self, height, speed):
super().__init__(height, speed)
self.person_title = "Hero"

was this the right way to do it?

Find elsewhere
🌐
Earthly
earthly.dev › blog › abstract-base-classes-python
Abstract Base Classes in Python - Earthly Blog
July 19, 2023 - It has two instance variables, length and width, which are passed in as parameters to the __init__ method. The area method calculates the area of the rectangle by multiplying the length and width together, while the perimeter method calculates the perimeter by adding the length and width and then multiplying the result by two. Let’s then look at an abstract base class that has abstract methods and one concrete method. # vehicle_I.py from abc import ABC, abstractmethod class Vehicle(ABC): @abstractmethod def start(self): pass @abstractmethod def stop(self): pass def beep(self): print("Beep beep!")
🌐
GitHub
github.com › python › mypy › issues › 1706
Adding @abstractmethod __init__ to ABC breaks staticmethods · Issue #1706 · python/mypy
June 14, 2016 - from abc import ( ABCMeta, abstractmethod, ) class WidgetWithInit(object): __metaclass__ = ABCMeta @abstractmethod def __init__(self, foo, bar): # type: (int, int) -> None pass @staticmethod def add(foo, bar): # type: (int, int) -> int return foo + bar @classmethod def add_class(cls, foo, bar): # type: (int, int) -> int return foo + bar WidgetWithInit.add(1, '2') WidgetWithInit.add_class(1, '2') class WidgetNoInit(object): __metaclass__ = ABCMeta @staticmethod def add(foo, bar): # type: (int, int) -> int return foo + bar @classmethod def add_class(cls, foo, bar): # type: (int, int) -> int return foo + bar WidgetNoInit.add(1, '2') WidgetNoInit.add_class(1, '2')
Author   euresti
🌐
Machine Learning Plus
machinelearningplus.com › python › python-abcs-the-complete-guide-to-abstract-base-classes
Python ABCs- The Complete Guide to Abstract Base Classes – Machine Learning Plus
pythonCopy · from abc import ABC, abstractmethod # Abstract base class for vehicles class Vehicle(ABC): def __init__(self, brand, model): self.brand = brand self.model = model @abstractmethod def start_engine(self): pass @abstractmethod def get_fuel_type(self): pass # Concrete method - common functionality def get_info(self): return f"{self.brand} {self.model}" The Vehicle class is abstract because it inherits from ABC and has methods decorated with @abstractmethod.
🌐
W3Schools
w3schools.com › python › ref_module_abc.asp
Python abc Module
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass class Square(Shape): def __init__(self, s): self.s = s def area(self): return self.s * self.s sq = Square(3) print(isinstance(sq, Shape)) print(sq.area()) Try it Yourself »
🌐
Python
peps.python.org › pep-3119
PEP 3119 – Introducing Abstract Base Classes | peps.python.org
This PEP proposes a particular strategy for organizing these tests known as Abstract Base Classes, or ABC. ABCs are simply Python classes that are added into an object’s inheritance tree to signal certain features of that object to an external inspector.
🌐
CodeFatherTech
codefather.tech › home › blog › create an abstract class in python: a step-by-step guide
Create an Abstract Class in Python: A Step-By-Step Guide
December 8, 2024 - $ python aircraft.py Traceback (most recent call last): File "aircraft.py", line 3, in <module> class Aircraft(ABC): File "aircraft.py", line 10, in Aircraft @property File "/Users/codefathertech/opt/anaconda3/lib/python3.7/abc.py", line 23, in abstractmethod funcobj.__isabstractmethod__ = True AttributeError: attribute '__isabstractmethod__' of 'property' objects is not writable · Let’s also override the constructor in the Jet class: class Jet(Aircraft): def __init__(self, speed): self.__speed = speed def fly(self): print("My jet is flying")
🌐
Plain English
python.plainenglish.io › understand-the-abc-class-and-the-magical-init-subclass-method-in-python-7d42ef99d993
Understand the ABC class and the magical __init_subclass__ method in Python | by Lynn G. Kwong | Python in Plain English
October 31, 2024 - The ABC class in Python stands ... instantiated. The __init_subclass__ method in Python is a special class method that is automatically called when a class is subclassed....
🌐
DataCamp
datacamp.com › tutorial › python-abstract-classes
Python Abstract Classes: A Comprehensive Guide with Examples | DataCamp
January 22, 2025 - The ABC class is a built-in Python feature that serves as a fundamental basis for developing abstract classes. You must inherit from ABC to define an abstract class. The class is abstract and cannot be instantiated directly, as indicated by this inheritance.
🌐
Reddit
reddit.com › r/learnpython › inherit __init__ from superclass/abc
r/learnpython on Reddit: Inherit __init__ from superclass/abc
January 9, 2016 -

I have several different metric reports that share multiple things in common. As such, I have created an ABC that they all inherit. However, I would like all subclasses to automatically inherit the defined init in the ABC without having to copy the variables over and over in my inheriting classes.

Here is a sample of what I'm doing:

class Metric(metaclass=ABCMeta):
    """
    Abstract class for all metrics to inherit from.
    """
    def __init__(self, startdate=None, enddate=None):
        self.startdate = startdate
        self.enddate = enddate

    @abstractclassmethod
    def execute(self):
        pass


class SampleReport(Metric):
    def __init__(self):
        super().__init__()

    def execute(self):
        pass

In this scenario I won't be able to instantiate SampleReport and set startdate & enddate. I found a Stackoverflow thread describing the exact problem I'm facing, but I don't see a good solution to the issues: http://stackoverflow.com/questions/6535832/python-inherit-the-superclass-init

🌐
Reddit
reddit.com › r/learnpython › what's the point of abc & @abstractmethod
r/learnpython on Reddit: What's the point of ABC & @abstractmethod
July 27, 2021 -

Hello. In this first example, I have a short and straightforward code w/ a class for interface. It doesn't inherit from ABC and doesn't have any abstract methods.

class Abs():
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    def go_to(self):
        return f"{self.name} is going to {self.place}."
        
class Teacher(Abs):
    place = "work"

class Student(Abs):
    place = "school"
    
t1 = Teacher("James", 56)
s1 = Student("Tim", 15)

print(t1.go_to())
print(s1.go_to())

In this second example, it's the exact opposite.

from abc import ABC, abstractmethod

class Abs(ABC):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    @abstractmethod
    def go_to(self):
        ...
        
class Teacher(Abs):
    place = "work"
    
    def go_to(self):
        return f"{self.name} is going to {self.place}."

class Student(Abs):
    place = "school"
    
    def go_to(self):
        return f"{self.name} is going to {self.place}."
    
t1 = Teacher("James", 56)
s1 = Student("Tim", 15)

print(t1.go_to())
print(s1.go_to())

Both examples have the same output. In the tutorials/articles I've read, most times the second example is preferred. In the abstract class, abstract methods get defined and decorated, and then in the inheriting classes they all get redefined with the rest of the logic. What's the point of creating a class w/ abstract methods which later on we redefine? What issue does that solve? Why not just proceed as in the first example - simple, less code, one parent class for the interface, if we need to add other details, we do so in the base class once and handle the extra logic with that additional info there. Doesn't the first code present a better example of loose coupling - just one connection between parent and child classes, where in the second code, we get connections between parent/child in every method that we redefine? I feel like I'm missing something, because to me, the second example is much more spaghetti-like. If anyone can explain why it's a good practice to redefine abstract methods that would be nice. Also, is it a bad practice to write code as in the first example, w/o ABC+@abstractmethod in the parent class?
Thanks.

Top answer
1 of 5
10
So your examples are a bit problematic because you would never use @abstractmethod in that situation. In your example there is no reason not to define the function only in the parent class--the parent knows everything it needs in order to execute the function, and the children don't change the execution at all. Also, Abs is a terrible name for a class. @abstractmethod is for when you: Require all children to have a method Don't have enough information to define that method in the parent Essentially, it "requires" child classes to define this method. This allows you to include the method in your parent interface so you can document it but raises a sensible error if the child doesn't re-define it. This is mostly useful for parent classes that will never have direct instances--only instances of subclasses. Consider designing a shooter game like Doom or Quake. You might represent various objects and enemies as class instances. To keep the game synced, every clock tick all the objects need to "update" themselves. Enemies might move around, lights might blink, and items might recharge. They all need to do something, but what they do is completely unique to each class. In a case like this, you might define the update() method in the parent Object class. This is mostly a convenience feature--you can write the same code perfectly well without it. However, it allows you to refer to all objects collectively (isinstance(o, Object)) through the parent class, and still ensure that update() exists, even though the parent doesn't know what to do with it. You could easily define update() in the parent and have it do nothing, but this prevents errors from being raised if you call this on a child class that hasn't re-defined the method.
2 of 5
3
let's imagine a List interface - we'll have the operations of append and pop class List(ABC): @abstractmethod def append(self, val): pass @abstractmethod def pop(self): pass now we could create class LinkedList(List) and class ArrayList(List) where we'd implement the methods for both of the list types the reason for using ABC and @abstractmethod is because it doesn't make sense to be able to be able to instantiate a List - that doesn't have an implementation. it only describes what behaviour an implementation should have to provide. think of it as providing a contract by which all users of an object know what behaviour to expect abstract classes and methods are more useful in languages such as java where you can't rely on duck typing void doThing(List list) this would take any subclass of List and be checked at compile time to have the expected methods of append and pop