I have a Python class like this:
class A:
__val1: float = 0.0
__val2: float
def __init__():
validate()
def validate() -> bool:
if not hasattr(self, __val2): # how is this supposed to be done?
raise NotImplementedError()
return self.__val1 >= self.val2
My goal is to use A
as an abstract class where the child classes are forced to implement __val2
.
I create a child class B
:
class B(A):
__val2 = 1.0
def __init__():
super().__init__()
When I initialize an object of class B
, this error is thrown:
E AttributeError: 'B' object has no attribute '_A__val2'
I tried modifying B
like this:
class B(A):
A.__val2 = 1.0
[...]
But this throws the same exception.
Trying the same but with super
:
class B(A):
super.__val2 = 1.0
[...]
But this throws another error:
E TypeError: can't set attributes of built-in/extension type 'super'
What is the Pythonic way do handle this kind of abstraction?
How should validate()
be implemented so that it checks for __val2
?