I have two classes in a parent-child relation. Variables are assigned values in the parent class and need to be updated in the child class if they are given in the function argument.
class ABC:
def __init__(self):
self.var_1 = 'a'
self.var_2 = 'b'
class XYZ(ABC):
def __init__(self, **kwargs):
# what to do here?
Above code is the structure for my project.
Now if I want to update value of any variable, how to do that?
For example, this is how it will work:
>>> a = XYZ()
>>> print(a.var_1)
a
I need it to work like this:
>>> a = XYZ(var_1='updated_value')
>>> print(a.var_1)
updated_value
CodePudding user response:
Here is a solution to your problem by accessing the __dict__ of the instance after the __init__ of the superclass:
# Calling the parent ABC is confusing, I thought you were refering to the Abstract Base Class (abc.ABC)
class Parent:
def __init__(self):
self.var_1 = 'a'
self.var_2 = 'b'
class XYZ(Parent):
def __init__(self, **kwargs):
super().__init__()
base_variables = self.__dict__
for k, v in kwargs.items():
if k in base_variables:
self.__setattr__(k, v)
a = XYZ(var_1='updated_value')
print(a.var_1)
>>> updated_value
Note: by comparing the key with self.__dict__, you make sure that no one can pass random kwargs
CodePudding user response:
I think you are looking for something like this:
class ABC:
def __init__(self) -> None:
self.var_1 = 'a'
self.var_2 = 'b'
class XYZ(ABC):
def __init__(self, **kwargs):
super().__init__()
if kwargs.get("var_1") is not None:
self.var_1 = kwargs["var_1"]
if __name__ == '__main__':
a = XYZ(var_1='updated_value')
print(a.var_1)