Python 3.3+

from abc import ABCMeta, abstractmethod


class A(metaclass=ABCMeta):
    def __init__(self):
        # ...
        pass

    @property
    @abstractmethod
    def a(self):
        pass

    @abstractmethod
    def b(self):
        pass


class B(A):
    a = 1

    def b(self):
        pass

Failure to declare a or b in the derived class B will raise a TypeError such as:

TypeError: Can't instantiate abstract class B with abstract methods a

Python 2.7

There is an @abstractproperty decorator for this:

from abc import ABCMeta, abstractmethod, abstractproperty


class A:
    __metaclass__ = ABCMeta

    def __init__(self):
        # ...
        pass

    @abstractproperty
    def a(self):
        pass

    @abstractmethod
    def b(self):
        pass


class B(A):
    a = 1

    def b(self):
        pass
Answer from Wtower on Stack Overflow
🌐
Python.org
discuss.python.org › ideas
Provide a canonical way to declare an abstract class variable - Ideas - Discussions on Python.org
October 28, 2024 - There’s a recent help post of Abstract variables in abc that asks about how an “abstract variable” can be declared such that it is required for a subclass to override the variable, to which @drmason13 replied: Although this approach of abusing an abstract property as an abstract variable ...
🌐
Nimc
vault.nimc.gov.ng › blog › python-abcs-abstract-class-variables-explained-1767649051
Python Abcs Abstract Class Variables Explained ...
Check any cables and reboot any routers, modems, or other network devices you may be using · If it is already listed as a program allowed to access the network, try removing it from the list and adding it again · Check your proxy settings or contact your network administrator to make sure ...
Discussions

oop - Abstract attributes in Python - Stack Overflow
Instead of pass or an elipsis (...) ... for the abstract method. pylint told me that. 2020-12-12T12:29:45.007Z+00:00 ... Thanks sausix, it's a good point. I'll include it into the answer 2020-12-13T11:42:17.05Z+00:00 ... As of Python 3.6 you can use __init_subclass__ to check for the class variables of the child ... More on stackoverflow.com
🌐 stackoverflow.com
Is there a such thing as declaring an attribute of an abstract class in Python?
You can do this with @property and @abstractmethod Py:3.3+ (@abstractproperty for earlier versions of python): from abc import ABC, abstractmethod class Base(ABC): @property @abstractmethod def name(self): pass class Concrete(Base): def __init__(self, name): self._name = name @property def name(self): return self._name In []: Base() Out[]: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In [56], line 1 ----> 1 Base() TypeError: Can't instantiate abstract class Base with abstract method name In []: Concrete("Name").name Out[]: 'Name' More on reddit.com
🌐 r/learnpython
24
9
February 9, 2023
[abc] Add abstract attributes via `abstract` type-hint - Ideas - Discussions on Python.org
Feature or enhancement Add a special generic type hint abstract, that allows specifying that subclasses must implement an attribute. from abc import ABC, abstract class Foo(ABC): myattr: abstract[int] # 100 upvotes) How to create abstract properties in python a... More on discuss.python.org
🌐 discuss.python.org
8
April 24, 2023
Abstract variables in abc
the ability to create abstract variables so you can encourage the user to override a class variable so you can encourage a user to override it More on discuss.python.org
🌐 discuss.python.org
0
October 24, 2024
People also ask

What is an abstract class in Python?
An abstract class in Python is a class that cannot be instantiated directly. It can include abstract methods that any subclass must implement.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › abstract class in python
Abstract Class in Python | With Example and Interface Comparison
Can an abstract class have properties in Python?
Yes, an abstract class in Python example can have abstract properties, which must be implemented by the subclass, just like abstract methods.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › abstract class in python
Abstract Class in Python | With Example and Interface Comparison
How do abstract classes help in Python?
Abstract classes in Python help enforce a structure for subclasses, ensuring that all required methods are implemented making code more organized and maintainable.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › abstract class in python
Abstract Class in Python | With Example and Interface Comparison
🌐
The Teclado Blog
blog.teclado.com › python-abc-abstract-base-classes
How to Write Cleaner Python Code Using Abstract Classes
October 26, 2022 - We use @abstractmethod to define a method in the abstract base class and combination of @property and @abstractmethod in order to define an abstract property. I hope you learnt something new today! If you're looking to upgrade your Python skills even further, check out our Complete Python Course.
Top answer
1 of 13
183

Python 3.3+

from abc import ABCMeta, abstractmethod


class A(metaclass=ABCMeta):
    def __init__(self):
        # ...
        pass

    @property
    @abstractmethod
    def a(self):
        pass

    @abstractmethod
    def b(self):
        pass


class B(A):
    a = 1

    def b(self):
        pass

Failure to declare a or b in the derived class B will raise a TypeError such as:

TypeError: Can't instantiate abstract class B with abstract methods a

Python 2.7

There is an @abstractproperty decorator for this:

from abc import ABCMeta, abstractmethod, abstractproperty


class A:
    __metaclass__ = ABCMeta

    def __init__(self):
        # ...
        pass

    @abstractproperty
    def a(self):
        pass

    @abstractmethod
    def b(self):
        pass


class B(A):
    a = 1

    def b(self):
        pass
2 of 13
127

Since this question was originally asked, python has changed how abstract classes are implemented. I have used a slightly different approach using the abc.ABC formalism in python 3.6. Here I define the constant as a property which must be defined in each subclass.

from abc import ABC, abstractmethod


class Base(ABC):

    @classmethod
    @property
    @abstractmethod
    def CONSTANT(cls):
        raise NotImplementedError

    def print_constant(self):
        print(self.CONSTANT)


class Derived(Base):
    CONSTANT = 42

This forces the derived class to define the constant, or else a TypeError exception will be raised when you try to instantiate the subclass. When you want to use the constant for any functionality implemented in the abstract class, you must access the subclass constant by type(self).CONSTANT instead of just CONSTANT, since the value is undefined in the base class.

There are other ways to implement this, but I like this syntax as it seems to me the most plain and obvious for the reader.

The previous answers all touched useful points, but I feel the accepted answer does not directly answer the question because

  • The question asks for implementation in an abstract class, but the accepted answer does not follow the abstract formalism.
  • The question asks that implementation is enforced. I would argue that enforcement is stricter in this answer because it causes a runtime error when the subclass is instantiated if CONSTANT is not defined. The accepted answer allows the object to be instantiated and only throws an error when CONSTANT is accessed, making the enforcement less strict.

This is not to fault the original answers. Major changes to the abstract class syntax have occurred since they were posted, which in this case allow a neater and more functional implementation.

🌐
Real Python
realpython.com › ref › glossary › abstract-base-class
abstract base class (ABC) | Python Glossary – Real Python
This is useful for ensuring that derived classes implement particular methods from the base class, providing a consistent interface for different parts of your program. To define an abstract base class, you inherit from abc.ABC and use the @abstractmethod decorator to mark methods that must be implemented by subclasses.
🌐
Earthly
earthly.dev › blog › abstract-base-classes-python
Abstract Base Classes in Python - Earthly Blog
July 19, 2023 - In the above code we have a Rectangle class that is a subclass of the Shape interface. 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 ...
Find elsewhere
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › abstract class in python
Abstract Class in Python | With Example and Interface Comparison
June 1, 2025 - Think of it as a blueprint—you define what methods must exist, but not how they work. Any class that inherits from it must implement those methods. Python provides this through the abc module (abc stands for Abstract Base Class)
🌐
W3Schools
w3schools.com › python › python_classes.asp
Python Classes
class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
Pydantic
docs.pydantic.dev › latest › concepts › models
Models - Pydantic Validation
Besides, using these abstract types can also lead to poor validation performance, and in general using concrete container types will avoid unnecessary checks. By default, Pydantic models won't error when you provide extra data, and these values will simply be ignored: from pydantic import BaseModel class Model(BaseModel): x: int m = Model(x=1, y='a') assert m.model_dump() == {'x': 1}
🌐
Python.org
discuss.python.org › ideas
[abc] Add abstract attributes via `abstract` type-hint - Ideas - Discussions on Python.org
April 24, 2023 - Feature or enhancement Add a special generic type hint abstract, that allows specifying that subclasses must implement an attribute. from abc import ABC, abstract class Foo(ABC): myattr: abstract[int] # <- subcla…
🌐
Python.org
discuss.python.org › python help
Abstract variables in abc - Python Help - Discussions on Python.org
October 24, 2024 - the ability to create abstract variables so you can encourage the user to override a class variable so you can encourage a user to override it
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.3 documentation
from dataclasses import dataclass @dataclass class Employee: name: str dept: str salary: int · >>> john = Employee('john', 'computer lab', 1000) >>> john.dept 'computer lab' >>> john.salary 1000 · A piece of Python code that expects a particular abstract data type can often be passed a class that emulates the methods of that data type instead.
🌐
Python
docs.python.org › 3 › library › abc.html
abc — Abstract Base Classes
The ABC MyIterable defines the standard iterable method, __iter__(), as an abstract method. The implementation given here can still be called from subclasses. The get_iterator() method is also part of the MyIterable abstract base class, but it does not have to be overridden in non-abstract derived classes.
🌐
Scaler
scaler.com › home › topics › abstract class in python
Abstract Class in Python - Scaler Topics
April 9, 2024 - As we have been told, properties are used in Python for getters and setters. Abstract property is provided by the abc module to force the child class to provide getters and setters for a variable in Python.
🌐
Refactoring.Guru
refactoring.guru › home › design patterns › creational patterns
Abstract Factory
January 1, 2026 - The first thing the Abstract Factory pattern suggests is to explicitly declare interfaces for each distinct product of the product family (e.g., chair, sofa or coffee table). Then you can make all variants of products follow those interfaces. For example, all chair variants can implement the Chair interface; all coffee table variants can implement the CoffeeTable interface, and so on. All variants of the same object must be moved to a single class hierarchy.
🌐
Medium
medium.com › @abhishekjainindore24 › embracing-abstraction-a-dive-into-abstract-classes-in-python-0faf6d83948d
Embracing Abstraction: A Dive into Abstract Classes in Python | by Abhishek Jain | Medium
September 8, 2024 - In this example, AbstractClass is an abstract class containing an abstract method abstract_method. Any class inheriting from AbstractClass must provide a concrete implementation for abstract_method.
🌐
Mypy
mypy.readthedocs.io › en › stable › class_basics.html
Class basics - mypy 1.19.1 documentation
class Base: def inc(self, x: int) ... · Mypy supports Python abstract base classes (ABCs). Abstract classes have at least one abstract method or property that must be implemented by any concrete (non-abstract) subclass....
🌐
Python.org
discuss.python.org › python help
Abstract variables in abc - #6 by drmason13 - Python Help - Discussions on Python.org
August 17, 2024 - Ah, I see you are correct. I was being lazy with syntax at the expense of semantics. You can implement the abstract property more precisely like this: class SubClass(BaseClass): # Implementing the abstract property @property def required_property(cls): return "I am from subclass" being a property you can still access it succinctly: SubClass().required_property However, since they want a class variable, and class properties are (I’ve just discovered) deprecated, it might...
🌐
CodeSignal
codesignal.com › learn › courses › revisiting-oop-concepts-in-python › lessons › understanding-abstract-classes-and-abstract-methods-in-python
Understanding Abstract Classes and Abstract Methods in ...
Think of it as a blueprint for other classes. It often includes one or more abstract methods. A class that inherits from an abstract class must implement all its abstract methods. In Python, the abc (Abstract Base Classes) module provides tools for defining abstract base classes.