Search code examples
pythongetter-setter

General setter for a class using strings


Let's say I have a class called "Employee" which was a bunch of different attributes. I can create a general getter which would basically get every attribute based on a string of its name like this but I don't know how to create a setter of the sort so I wouldn't have to do something like employee1.age = 22 every time. And creating multiple setter for every attribute would be pretty messy.

class Employee:

    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.address = "Somewhere"
        self.job = None

    def getter(self, name):
        return getattr(self, name, None)

    def setter(self, name, amount):
        pass

Solution

  • You can use setattr() and wrap it in your setter method like this:

        def setter(self, name, amount):
            return setattr(self, name, amount)
    

    So you'd call it like this

    e = Employee("Albert", 169)
    e.setter("age", 16)
    

    and when you check now for e.age you will see

    >>> e.age
    16