0

What's the safest approach to going about requiring inheritance? Currently I'm doing something similar to this:

>>> class A:  # Never instantiate by itself.
...     def a(self):
...         self.foo()
... 
... class B(A):
...     def foo(self):
...         print('123')
... 
... class C(A):
...     def foo(self):
...         print('456')
...         
>>> B().a()
123
C().a()
456
>>> A().a()  # Expect an error.
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 3, in a
AttributeError: 'A' object has no attribute 'foo'

Is this the best approach?

Dillon Miller
  • 763
  • 1
  • 6
  • 18

1 Answers1

0

You can use abstractmethod and ABC from the abc module:

In [1]: from abc import ABC, abstractmethod                                                    

In [2]: class A(ABC): 
   ...:     @abstractmethod 
   ...:     def foo(self): 
   ...:         ... 
   ...:                                                                        

In [3]: class B(A): 
   ...:     def foo(self): 
   ...:         print("ok") 
   ...:                                                                        

In [4]: class C(A): 
   ...:     def not_foo(self): 
   ...:         pass 
   ...:                                                                        

In [5]: c = C()                                                                
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-1ef1f2c22529> in <module>
----> 1 c = C()

TypeError: Can't instantiate abstract class C with abstract methods foo

By defining the base class as an abstract class and setting abstractmethod decorator to a method, you can require the method to be subclassed.

colidyre
  • 4,170
  • 12
  • 37
  • 53