How to force subclasses to implement a field using abstract base class in Python?

223 Views Asked by At

Abstract base class can force implementation of a method by all it's child classes using @abstractmethod decorator. Can the same be done with class fields?

Say we have the following classes:

from abc import ABCMeta, abstractmethod


class AbsHero(metaclass=ABCMeta):
    @abstractmethod
    def say_hello():
        """Hero greeting"""
    

class GoodHero(AbsHero):
    def __init__(name: str):
        self.name = name
        
    def say_hello():
        print('Hi, my name is ' + self.name + '.')
        
        
class SneakyHero(AbsHero):
    def say_hello():
        print("I am sneaky, I don't have a name")

I want to enforce all children of AbsHero to have name field, or at least property. Right now both child classes are valid. What can I do, to make GoodHero class to work well, but SneakyHero declaration to cause failure?

0

There are 0 best solutions below