0

this is a same representation of my code and I just want to know if there is a way to obtain the result of the second action (word1) from the first action (word). The main objective here is that if I change the variable letter, the assigned value should also be in respective to the variable inside the class.

class Test():
    def __init__(self, x='world'):
        self.a = 'hi {}'.format(x)
        self.b = 'hello'
        self.c = 'hey'


letter = 'a'
word = "Test(x='{}').{}".format('new world', letter)
print(word)
# prints Test(x='new world').a, expected 'hi new world'

word1 = Test(x='new world').a
print(word1)
# prints 'hi new world'
Ninja Warrior 11
  • 362
  • 3
  • 17

1 Answers1

0

If you're trying to get an attribute from an object, and you have a string containing the name of that attribute, you can use getattr:

class Test():
    def __init__(self, x='world'):
        self.a = 'hi {}'.format(x)
        self.b = 'hello'
        self.c = 'hey'

x = Test("new world")

letter = "a"
print(getattr(x, letter))
#output: hi new world

letter = "b"
print(getattr(x, letter))
#output: hello

If you're thinking "ok, but I don't want to have to call getattr more than once; I want to do word = getattr(x, letter) a single time, and have it automatically update every time I change letter after that". Unfortunately, that's not possible with ordinary strings, since strings are immutable. You can't change the value of a string object after it's created. You can change what the name word refers to, but that would require an assignment statement each time.

Kevin
  • 74,910
  • 12
  • 133
  • 166