0

I've seen some different ways to implement abstract methods, like:

First Method: importing ABC

from abc import ABC

class X(ABC):
    @abstractmethod
    def abstractmethod(self):
        pass

Second method: raise NotImplementedError

class X:
    def abstractmethod(self):
        raise NotImplementedError

I want to know two different things.

1) Which is the most accepted way to treat abstraction in Python?; and

2) How do I approach this for variables?

1 Answer 1

1

It mostly comes down to preference, I think, but from what code I've seen, the ABC way is more accepted, as it offers an extra safety guarantee of not letting you instantiate any class that includes methods tagged as abstract with the @abstractmethod decorator.

For variables, you can use the @property decorator on top of the @abstractmethod, like this

from abc import ABC, abstractmethod


class Test(ABC):
    @property
    @abstractmethod
    def test(self):
        pass


class TestImpl(Test):
    @property
    def test(self):
        return 1


Test()  # TypeError: Can't instantiate abstract class Test with abstract methods test
TestImpl().test  # 1
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.