python enforcing class variables in subclass

Solutions on MaxInterview for python enforcing class variables in subclass by the best coders in the world

showing results for - "python enforcing class variables in subclass"
Lena
16 Feb 2020
1class Foo:
2
3    page_name = None
4    author = None
5
6    def __init_subclass__(cls, **kwargs):
7        for required in ('page_name', 'author',):
8            if not getattr(cls, required):
9                raise TypeError(f"Can't instantiate abstract class {cls.__name__} without {required} attribute defined")
10        return super().__init_subclass__(**kwargs)
11
12
13class Bar(Foo):
14    page_name = 'New Page'
15    author = 'eric'
16
similar questions