You can use **kwargs and force the users to only pass keyword argument. Then it's easy to iterate over them and use setattr():
class A:
def update_parameters(self, **kwargs):
for k, v in kwargs.items():
if v is not None:
setattr(self, k, v)
but this has a problem, Any not-none values are going to be added to the instance's dictionary. So maybe you can add another check to see if the k is valid.
class A:
def update_parameters(self, **kwargs):
for k, v in kwargs.items():
if k in valid_attrs and v is not None:
setattr(self, k, v)
Or even use the instance's __dict__:
def update_parameters(self, **kwargs):
for k, v in kwargs.items():
if k in self.__dict__ and v is not None:
setattr(self, k, v)
Here is the complete code:
class A:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def update_parameters(self, **kwargs):
for k, v in kwargs.items():
if k in self.__dict__ and v is not None:
setattr(self, k, v)
def __repr__(self):
return f"A(a={self.a}, b={self.b}, c={self.c})"
obj = A(10, 20, 30)
print(obj)
obj.update_parameters(b=40, c=50, d=60)
print(obj)
output:
A(a=10, b=20, c=30)
A(a=10, b=40, c=50)
This ignores the d=60 value. If you want you can raise exception.