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
  • 51
  • 1
  • 1
  • 5

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
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Metalgear
  • 3,391
  • 1
  • 7
  • 16
0

You can use getattr for this.

self.value = getattr(myConfigConstants, strVariableName)
Rinkesh P
  • 588
  • 4
  • 13