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.
🌐
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
May 5, 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