Reputation: 457
I have been trying to update only those members of an object passed into a function which are truthy but I feel like my approach is bad for updating them.
Here's my approach:
class A:
def __init__(self, name, age, _id):
# Data Members
self.name = name
self.age = age
self._id = _id
def update(self, name=None, age=None, _id=None):
# These need to be updated if the parameters are truthy
if name:
self.name = name
if age:
self.age = age
if _id:
self._id = _id
It looks okay-ish if the members are less but If more members need to be updated, it becomes a mess.
How can this approach be improved?
Upvotes: 1
Views: 477
Reputation: 780879
Take the parameters as a dictionary and loop over it.
def update(self, **kwargs):
for name, val in kwargs.items():
setattr(self, name, val)
BTW, checking for truthy values is not a good idea if legitimate values can be falsey (e.g. setting an attribute to 0
). It would be better to use if name is not None:
-- this just assumes that None
is not a legitimate value.
Full code:
class A:
def __init__(self, name, age, _id):
# Data Members
self.name = name
self.age = age
def update(self, **kwargs):
for name, val in kwargs.items():
setattr(self, name, val)
foo = A("Barry", 59, 1234)
foo.update(name = "Joe", age = 10)
print(foo.name)
Upvotes: 3