0

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
  • Creating a general getter and setter may not be necessary. You can pass the age information on the creation of the class instance. https://stackoverflow.com/questions/11421659/passing-variables-creating-instances-self-the-mechanics-and-usage-of-classes – L.Clarkson Sep 12 '21 at 15:58
  • @L.Clarkson Didn't exactly solve the problem but thanks :thumbs-up: – GrantWard101 Sep 12 '21 at 16:04
  • Possible duplicate of this question https://stackoverflow.com/questions/13376135/passing-an-python-class-attribute-given-a-string – L.Clarkson Sep 12 '21 at 16:06
  • @L.Clarkson Yeah I think you're right. Should I close the question? – GrantWard101 Sep 12 '21 at 16:32
  • I can mark as duplicate – L.Clarkson Sep 12 '21 at 19:16
  • Does this answer your question? [Passing an Python Class Attribute Given a String](https://stackoverflow.com/questions/13376135/passing-an-python-class-attribute-given-a-string) – L.Clarkson Sep 12 '21 at 19:17

2 Answers2

0

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
0

Thanks to Joe Carboni's answer, I managed to create a function I'd like to call the ultimate_getter(). I'll put it here for you all to use.

def ultimate_getter(obj, name, limit = 12):

    if name.count(".") == 0:
        return getattr(self, name, None)

    else:
        count = 0
        previous = None
        current = None
        previous = obj

        while name.count(".") > 0 and count < limit:
            index = name.find(".")
            previous = getattr(previous, name[0:index])
            name = name[index + 1:]
            count += 1

            if name.count(".") == 0:
                current = getattr(previous, name)

        return current

It's basically a more advanced version of setattr() which can loop through the text so you wouldn't have to use setattr() a bunch of times when wanting to use sort of a nested attribute/method.