Whereas with Protocols it's gonna be ( good tutorial ): I think that is not a good example of how to write programs. What he did by having protocols I would have done by using mixins. The way that I see objects is that they have various capabilities that can be mixed in. multiple inheritance in python would have been a much better way to implement that example in my opinion. I would also say that the author of this tutorial needs to learn a thing or 2 about an inversion of control and dependency injection. The author basically sets up a straw man problem and then solves his straw man problem. He had no business creating instances of the object outside of the class itself. If he had simply called a constructor methods within the classes then the other class wouldn't have been attempting to make instances of those other classes. Answer from thedeepself on reddit.com
🌐
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
🌐
Reddit
reddit.com › r/python › what's the point of abstract classes if they don't enforce method signatures?
r/Python on Reddit: What's the point of abstract classes if they don't enforce method signatures?
December 18, 2016 -

I was surprised to see the Python abstract classes don't enforce anything except the override and method name. I can see why in Python enforcing parameter data-types would probably not work, but the number of parameters and parameter names ought to be enforced.

I've always thought the point of abstract classes was to ensure that any inheritor of the class would would work with existing code to run the abstract methods defined in the super class. The whole point was to enforce method signatures.

It seems to me that Python's implantation of abstract classes has very little utility. Does anyone even use them? What for?

🌐
Reddit
reddit.com › r/python › interfaces with protocols: why not ditch abc for good?
r/Python on Reddit: Interfaces with Protocols: why not ditch ABC for good?
January 22, 2023 -

Hello, if one finds interfaces useful in Python (>=3.8) and is convinced that static type-checking is a must, then why not ditch ABC and always use Protocols? I understand that the fundamental idea of a protocol is slightly different from an interface, but in practice, I had great success replacing abc's with Protocols without regrets.

With abc you would write (https://docs.python.org/3/library/abc.html) :

from abc import ABC, abstractmethod

class Animal(ABC):
   @abstractmethod
   def eat(self, food) -> float:
       pass

Whereas with Protocols it's gonna be (good tutorial):

from typing import Protocol

class Animal(Protocol):
   def eat(self, food) -> float:
       ...

Scores in my subjective scoring system :)

CapabilityABCProtocols
Runtime checking11 (with a decorator)
Static checking with mypy11
Explicit interface (class Dog(Animal):)11
Implicit interface with duck-typing (class Dog:)0.5 (kind of with register, but it doesn't work with mypy yet)1
Default method implementation (def f(self): return 5)-1 (implementations shouldn't be in the interfaces)-1 (same, and mypy doesn't catch this)
Callback interface01
Number of code lines-1 (requires ABC inheritance and abstracmethod for every method)0 (optionalProtocol inheritance)
Total score1.54

So I do not quite see why one should ever use ABC except for legacy reasons. Other (IMHO minor) points in favour of ABC I've seen were about interactions with code editors.

Did I miss anything?

I put more detailed arguments into a Medium. There are many tutorials on using Protocols, but not many on ABC vs Protocols comparisons. I found a battle of Protocols vs Zope, but we are not using Zope, so it's not so relevant.

🌐
Reddit
reddit.com › r/python › protocols vs abstract base classes in python
r/Python on Reddit: Protocols vs Abstract Base Classes in Python
December 1, 2024 -

Hi everyone. Last time I shared a post about Interface programming using abs in Python, and it got a lot of positive feedback—thank you!

Several people mentioned protocols, so I wrote a new article exploring that topic. In it, I compare protocols with abstract base classes and share my thoughts and experiences with both. You can check it out here: https://www.tk1s.com/python/protocols-vs-abstract-base-classes-in-python Hope you'll like it! Thanks!

Top answer
1 of 5
11

From the docs:

A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden.

Conversely, this means that any class with no abstract methods or properties like your AbstractClass can be instantiated.


If you want to disallow instantiation of the topmost parent class, you can write a custom class that performs a type check in its __new__ method:

class SubclassOnlyABC(object):
    __metaclass__ = abc.ABCMeta

    def __new__(cls, *args, **kwargs):
        if cls.__bases__ == (SubclassOnlyABC,):
            msg = 'Abstract class {} cannot be instantiated'.format(cls.__name__)
            raise TypeError(msg)

        return super(SubclassOnlyABC, cls).__new__(cls, *args, **kwargs)
class AbstractClass(SubclassOnlyABC):
    pass

class ChildClass(AbstractClass):
    pass

ChildClass()  # works because it's a child class of an abstract class
AbstractClass()  # throws TypeError because its parent class is "object"

You can also write a __new__ method that prevents instantiation of classes with no abstract methods:

class NonEmptyABC(object):
    __metaclass__ = abc.ABCMeta

    def __new__(cls, *args, **kwargs):
        # check if ANY abstractmethod exists
        for parentcls in cls.__mro__:
            if any(getattr(attr, '__isabstractmethod__', False)
                               for attr in vars(parentcls).values()):
                break
        else:
            msg = 'Abstract class {} cannot be instantiated'.format(cls.__name__)
            raise TypeError(msg)

        return super(NonEmptyABC, cls).__new__(cls, *args, **kwargs)
class EmptyAbstractClass(NonEmptyABC):
    pass

class NonemptyAbstractClass(NonEmptyABC):
    @abc.abstractmethod
    def foo(self):
        pass

class NonemptyChild(NonemptyAbstractClass):
    def foo(self):
        pass

NonemptyChild()  # works because "foo" is an abstractmethod
EmptyAbstractClass()  # throws TypeError because there are no abstractmethods
2 of 5
10

I usually just declare the base class's __init__ with @abc.abstractmethod. If my base class does not have an __init__, I add a trivial one.

Something like this:

class AbstractClass(abc.ABC):
    @abc.abstractmethod
    def __init__(self):
        pass

    # other useful non-abstract methods...


class ChildClass(AbstractClass):
    def __init__(self):
        pass


if __name__ == '__main__':
    child = ChildClass()  # allowed
    abstract = AbstractClass()  # TypeError
🌐
Stack Overflow
stackoverflow.com › questions › 46726272 › how-to-create-abstract-classes-using-abc-without-using-an-abstract-method
python - How to create abstract classes using abc without using an abstract method? - Stack Overflow
However, if you want to prevent it in the instantiation, you should rather use ABC's. You can also delcare __init__ an abstractmethod, but generally this does not look very useful to me.
🌐
Reddit
reddit.com › r/python › python interfaces: choose protocols over abc
r/Python on Reddit: Python Interfaces: Choose Protocols Over ABC
February 12, 2023 - Most likely you're a Java programmer who is wondering where all your boilerplate code went when you switched to Python 🙂 ... Protocols just make your duck typing explicit. Base classes are helpful but id avoid using them in typing. ... For me this misses the biggest benefit of using ABC over Protocol and the reason I don’t really bother with them.
🌐
Reddit
reddit.com › r/learnpython › struggling with abstraction in python
r/learnpython on Reddit: Struggling with Abstraction in Python
June 7, 2025 -

I an currently learning OOP in python and was struggling with abstraction. Like is it a blueprint for what the subclasses for an abstract class should have or like many definitions say is it something that hides the implementation and shows the functionality? But how would that be true since it mostly only has pass inside it? Any sort of advice would help.

Thank you

Top answer
1 of 5
8
"Abstraction" is a broader term than you might be thinking. Basically, what do a bunch of concrete examples have in common? Give that a definition, and that's an abstraction. If you're asking about abstract base classes (ABCs) in particular, the collections.abc module of the standard library has good examples. You can use a set, a dict, a list, a tuple, or a generator function in a for loop. The collections module has more (like a deque). Despite being completely separate types, they're all "iterables" in abstract, and support a common protocol for getting an iterator object, which is itself an abstraction for getting all the elements, one at a time. Your classes can support the same protocols, and basing them on the relevant ABCs, some of the protocol may be implemented for you and it plays nice with the type system (like using isinstance() or static types to check if something supports the protocol). The "mixin" methods are defined in terms of the abstract ones.
2 of 5
2
When learning OOP you should go beyond the actual language implementation and learn the philosophy and the idea behind it, not just how a language implements it. For example, you shouldn't care about "pass" at all, you need to look beyond that. In OOP you create a blueprint, true. This blueprint is usually known as protocol (or interface in imperative programming like C++, Java, C#, Python, etc) and declares a number of elements like attributes and messages (or methods in imperative programming) that any class wanting to be recognized as derived of the blueprint must implement. Since the blueprint simply declares messages the implementation can receive (methods you can call in imperative programming) they don't need to have an implementation. A bit more concrete: since you only need the signatures of the methods they don't need a body, and most languages support empty bodies when declaring an interface (which is literally a semicolon in C# or open-close curly brackets {} in C++). Python, unfortunately, cannot use either of them, so it's forced to use pass. As you see, it's just an implementation limitation by the language, not something defined by the paradigm itself. There's a small variation which is that you can have default handlers for determined messages, or in other words you can have default implementations for those inherited methods. C# recently implemented default implementations in interfaces (which is horrible personally but it's in order to be able to maintain compatibility while extending interfaces) but you can see that usually as abstract or virtual classes, classes that inherit from this blueprint but offer a default handling so that those inheriting from it don't need to implement functionality for messages they don't want to handle. In truth I wouldn't suggest using Python to learn OOP because it has some quirks that confuse people. For example, changing the list of parents of a class will change the order in which they are called which is extremely flimsy, just someone sorting the parents alphabetically can break your application and you might spend days trying to find out why. Which also means you can have multiple inheritance which is something most languages have dropped altogether (with C++ and Python being like the only two modern languages still supporting it). I understand, though, if you are forced to learn OOP with Python due school or some assignment.
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › do abc and @abstractmethod always go together?
r/learnpython on Reddit: Do ABC and @abstractmethod always go together?
January 23, 2025 -

Consider the following code. Note the comments in particular:

from abc import ABC, abstractmethod

# func1 MUST be overridden
# func2 may be overridden
class Class1(ABC):
	@abstractmethod 
	def func1(self):
		pass #any code here is useless
	def func2(self):
		print('fallback message')       
	
	
# func1, func2 may be overridden
# @abstractmethod does nothing
# Effectively same as Class3, Class4
class Class2():
	@abstractmethod
	def func1(self):
		pass        
	def func2(self):
		pass           
	

# func1, func2 may be overridden 
# Inheriting from ABC does nothing
# Effectively same as Class4, Class2
class Class3(ABC): 
	def func1(self):
		pass        
	def func2(self):
		pass           
	
	
# func1, func2 may be overridden
# Effectively same as Class3, Class2
class Class4():
	def func1(self):
		pass        
	def func2(self):
		pass               

Assuming my comments are valid, am I correct in thinking that the @abstractmethod decorator only makes sense when used in conjunction with an ABC class? (i.e., Class1)

🌐
GitHub
github.com › microsoft › pyright › issues › 2547
No errors when using `@abstractmethod` on non-ABC class or when instantiating such class · Issue #2547 · microsoft/pyright
November 6, 2021 - To Reproduce # pyright: strict from abc import abstractmethod class MyAbstract: # does not inherit from ABC @abstractmethod # no error def do_something(self): pass c = MyAbstract().do_something() # also no error Expected behavior An erro...
Author   Tomaz-Vieira
🌐
Python.org
discuss.python.org › python help
AbstractMethods and NotImplementedError - Python Help - Discussions on Python.org
December 22, 2022 - The documentation for the exception says that abstract methods should raise NotImplementedError. Obviously this is not mandatory. Abstract methods can have default implementations.
🌐
Reddit
reddit.com › r/learnpython › am i understanding abstract classes correctly?
r/learnpython on Reddit: Am I understanding Abstract Classes correctly?
March 22, 2017 -

I'm currently taking an Udemy course on classes but unfortunately the section on Abstract Classes doesn't go into a whole lot of depth. I have a few questions as well as some sample code I wrote that I'd like to make sure is properly written.

  1. What exactly is the point of abstract classes? My first take is that it would be used in an environment where there are several developers where one may be writing the abstract class but wants to make it obvious that the child classes need specific methods/attributes. It also ensures that an instance cannot be made from the abstract class. Are they other reasons to use an abstract class that I'm not thinking of?

  2. Googling for clarification, I've seen a couple different implementations of the abc module. What's the different of each?

    MyClass(metaclass=abc.ABC): ...

    MyClass(metaclass=abc.ABCMeta): ...

    MyClass: __metaclass__=abc.ABCMeta ...

From what I can tell, the first example is for Python 3.4+, the second is for Python 3.0+, and the last is for Python 2.X. My confusion comes from the below example. I'm using Python 3.4 but (metaclass=abc.ABC) doesn't work while (metaclass=abc.ABCMeta) does. 

3. My last question is just for a sanity check. Is the below code properly using both inheritance and abstract classes? Is there a better or more Pythonic way to do it?

    from abc import ABCMeta, abstractmethod


    class Vehicle(metaclass=ABCMeta):

        @abstractmethod
        def __init__(self, year, miles, make, model):
            self.year = year
            self.miles = miles
            self.make = make
            self.model = model
            self.sold_on = None

        def sold_date(self, date):
            self.sold_on = date


    class Car(Vehicle):
        def __init__(self, year, miles, make, model):
            super().__init__(year, miles, make, model)
            self.wheels = 4
            self.doors = 4


    class Motorcycle(Vehicle):
        def __init__(self, year, miles, make, model):
            super().__init__(year, miles, make, model)
            self.wheels = 2
            self.doors = 0
Top answer
1 of 2
2
What exactly is the point of abstract classes? They are a way to formally document the interface to a Class. Kind of. ABCs are also a solution looking for a problem. They were based on any real-world problems or designed to solve specific use cases. Is there a better or more Pythonic way to do it? Technically, the term "abstract" refers to only the method signature and doc string of a method. Python doesn't have any way to only write abstract methods without mandatorily including the concrete part of the method. e.g. def foo(self, arg1): <-- abstract """Take arg1 and add 1 to it and return the value""" <-- abstract return arg1 + 1 <-- concrete So when using ABCs it's possible to mix implementation with definition, for better or worse. Better maybe for smaller or simpler programs, but for larger applications it's going to be cleaner to not have implementation bits sneak into ABCs. In your example you might have: class VehicleABC(metaclass=ABCMeta): @abstractmethod def __init__(self, year, miles, make, model): pass class Vehicle(VehicleABC): def __init__(self, year, miles, make, model): self.year = year self.miles = miles self.make = make self.model = model self.sold_on = None def sold_date(self, date): self.sold_on = date When your ABC doesn't do anything, then it's doing it right. If you really want to have formal docs for your Classes though, look at the zope.interface package. It's been around longer than the ABC package, is more feature complete and doesn't have the design flaws that ABCs do of messing with the inheritance hierarchy to denote Class metadata.
2 of 2
1
ABC is a 'normal' class with ABCMeta set as its metaclass. You should just subclass it normally (using it as a metaclass doesn't make sense). That will inherit the metaclass specification. You could also directly set the metaclass with metaclass=. Those function the same, but the first is a little bit nicer looking (you just say it's an ABC, and don't specify the exact internals used to make that work). The __metaclass__ thing is a Python 2 syntax which was used before keyword support was added to the base section of the class definition.
🌐
Reddit
reddit.com › r/learnpython › should i use *args and **kwargs with abstract method?
r/learnpython on Reddit: Should I use *args and **kwargs with abstract method?
August 28, 2025 -

I am working in research where I am using python (numpy, scikit-learn, matplotlib mostly) to solve an optimization problem. I have a parent class where most of the code is, but we want to try two different methods for part of the optimization, so I have two child classes (one for each). I am using @ abstractmethod in the parent for the function, then I want to implement in the children.

The children implementations will not have the same parameters. Should I use *args and **kwargs in the parent implementation, or does it not matter and I can just do

@abstractmethod
def func(self):
  pass

and then in the children's implementations pass whatever I need:

class Child1(Base):
  def func(self, var1, var2):
    do_stuff
🌐
GitHub
github.com › python › cpython › issues › 100400
You don't need to raise NotImplementedError for abstract methods · Issue #100400 · python/cpython
December 21, 2022 - If "abstract base classes" are meant to mean ABCs from the standard library, this is unnecessary as the ABC metaclass will prohibit instantiation of any derived class that doesn't implement an abstract method.
Author   Xophmeister
🌐
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?

🌐
Python.org
discuss.python.org › typing
Calling abstract methods - Typing - Discussions on Python.org
January 6, 2024 - PEP 544 indicates that a type checker should generate an error if a class that explicitly derives from the protocol attempts to call a method through super() if that method is unimplemented in the protocol. class Proto(Protocol): def method(self) -> None: ... class Impl(Proto): def method(self) -> None: super().method() # Type checker error This makes sense because the method in the protocol is effectively abstract.
🌐
Python
docs.python.org › 3 › library › abc.html
abc — Abstract Base Classes
Dynamically adding abstract methods ... supported using the update_abstractmethods() function. The abstractmethod() only affects subclasses derived using regular inheritance; “virtual subclasses” registered with the ABC’s register() ...