1

I am trying to fetch a variable value by passing the variable name into a calling function. My intention is to get the variable value based on the variable name passed as parameter.

class myConfigConstants():
    Name = "XYZ"
    Address = "abcd"
    Age = 10

    def __init__(self):
        self.value = ""

    def fetch_myConfigConstants(self, strVariableName: str):
        self.value = myConfigConstants.strVariableName
        print(self.value)
        return self.value

mc = myConfigConstants()
mc.fetch_myConfigConstants('Name')

Expected output: XYZ

This results in error: AttributeError: type object 'myConfigConstants' has no attribute 'strVariableName'

I understand that it is looking for the exact attribute, but how to make passed parameter name resolves into actual attribute at runtime.

pradeep
  • 13
  • 4

2 Answers2

0

You can use getattr function.

getattr(self, strVariableName)

In your code,

...
def fetch_myConfigConstants(self, strVariableName: str):
    self.value = getattr(self, strVariableName)
    print(self.value)
    return self.value

Hope it could help.

David Lu
  • 2,160
  • 1
  • 5
  • 14
0

You can use getattr for this.

self.value = getattr(myConfigConstants, strVariableName)
Rinkesh P
  • 454
  • 2
  • 11