0

This is what I'm talking about:

For example:

class User():
    def __init__(self, username, fullname):
        self.username = username
        self.fullname = fullname

    def update(self, arg, value):
        if arg is 'username':
            self.username = value
        elif arg is 'fullname':
            self.fullname = value

In the update function I am letting the user input a param they want to update, arg, with the value specified, value.

If I ever wanted to add more args to the User class, I would need to change the update function as well with the added arguments. How can I create a dynamic update function that accepts any of the existing arguments in the class __init__?

Ex: If I added email arg to __init__(), I would need to add this to the update() function:

if arg is 'email':
    self.email = value

^ this would get annoying after a while.

I hope you understand what I'm asking. If you need any more clarification let me know

Doc Oliver
  • 31
  • 1
  • 3
  • 1
    There's a builtin function that already does this, it's called setattr. – Paul M. Aug 04 '19 at 23:27
  • 1
    Possible duplicate of [How to access object attribute given string corresponding to name of that attribute](https://stackoverflow.com/questions/2612610/how-to-access-object-attribute-given-string-corresponding-to-name-of-that-attrib) – Mike Scotty Aug 04 '19 at 23:27
  • `setattr(self, arg, value)` would work any param in `update()` method. – martineau Aug 04 '19 at 23:46
  • Why do you need this? What is stopping you from setting the attributes? Like `x.username = blah` instead of `x.update('username', blah)`? If `username` is a string naming a variable, so `setattr(x , 'username', blah)` – Mad Physicist Aug 05 '19 at 00:00

1 Answers1

0

You just need to generalise your update function, like this:

def update(self, arg, value):
    setattr(self, arg, value)

Then...

>>> john = User('teraspora', 'John Lynch')
>>> john.username
'teraspora'
>>> john.update('username', 'Aladdin')
>>> john.username
'Aladdin'

Hope this helps!

teraspora
  • 415
  • 4
  • 17