0

I am trying to use a function inside of a class that uses a variable to change attributes of objects within that class.

class test():

    value_1 = "none"
    value_2 = "goodbye"
    value_3 = "hello"

    def labelator(self, var):

        if var != "hello" or "goodbye":
            setattr(self, var, "hello")

        elif var == "hello":
            setattr(self, var, "goodbye")
        else:
            setattr(self, var, "hello")

        return var

This is a test to see if the code is working:

obj = test()

print("Before change value_1 = " + str(getattr(test, 'value_1')))

print("Change with function so value_1 = " + str(obj.labelator(obj.value_1)))

print("Verify that class object has changed: value_1 = " + str(getattr(test, 'value_1')))

In this case, I want to change the object: value_1, with attribute: "none", to "hello".

Output:

Before change value_1 = none

Change with function so value_1 = none

Verify that class object has changed: value_1 = none

I beleive that the problem is that the variable referencing value_1 is being treated as the attribute instead of the object value_1, and I do not know how to fix this problem. Any help would be greatly appreciated.

Pedro Maia
  • 2,590
  • 1
  • 4
  • 20
try_hard
  • 11
  • 3
  • Yes your code in `obj.labelator(obj.value_1)` has obj.value_1 as "none" so you end up calling `setattr(self, 'none', "hello")` which sets self.none = "hello". To do what you intend, call `obj.labelator('value_1')` instead. I verified this in a REPL.it py doc at https://replit.com/@ToniAlatalo/WrongGrouchyLoopfusion#main.py – antont Jan 02 '22 at 00:23

0 Answers0