I have a classmethod
that I want to be called automatically before or when any child of the class it belongs to gets created. How can I achieve that?
Since I understand this can be an XY problem, here is why I (think I) need it, and my basic implementation.
I have a class that gets inherited, and the children of that class can specify a list of parameters that need to be converted into properties. Here is the relevant code:
class BaseData:
@staticmethod
def internalName(name: str) -> str:
return '_' + name
def __init__(self):
for k, v in self._dataProperties.items():
setattr(self, BaseData.internalName(k), v)
self._isModified = False
@classmethod
def initProperties(cls):
for k, v in cls._dataProperties.items():
# Create dynamic getter and setter function
getterFunc = eval(f'lambda self: self.getProperty("{k}")')
setterFunc = eval(f'lambda self, v: self.setProperty("{k}", v)')
# Make them a property
setattr(cls, k, property(fget=getterFunc, fset=setterFunc))
class ChildData(BaseData):
_dataProperties = {
'date': None,
'value': '0',
}
ChildData.initProperties()
Function initProperties
need to be called once for each child, and to enforce that I need to write it below function definition. I find it a bit ugly, so.. Is there any other wat to do it?
I already tried to put the code in __init__
, but it does not get called when I unpickle the objects.
So, basically:
- Generic question: is there any way to force a function to be called the first time a child class is used (even when
__init__
does not get called)? - If not, more specific question: is there a way to automatically call a specific function (it can be
__init__
, but also another one) when unpickling? - If not, single use-case question: Is there a better way to do what I'm doing here?
I already read Python class constructor (static), and while it has the same question I did not find a reply that could solve my use case.