0

I am trying to call an object from a variable. I know how to use getattr to call a function of an object using a variable but can't work out how to use a variable to define the object name. I have dragged some example code below:

class my_class(object):
    def __init__(self, var):
        self.var1 = var

var = "hello"
object_1 = my_class(var)

print object_1.var1 # outputs - hello

attribute = "var1"

# i can call the attribute from a variable

print getattr(object_1, attribute) # outputs - hello

object = "object_1"

# but i do not know how to use the variable "object" defined above to call the attribute

# now i have defined the variables object and attribute how can i use them to output "hello"?
deceze
  • 510,633
  • 85
  • 743
  • 889

1 Answers1

1

Since object_1 and object are global variables, you may use the code below:

print(globals()[globals()['object']].var1)   # "hello" is printed

or this:

print(getattr(globals()[globals()['object']], attribute))    # "hello" is printed

where

globals()['object'] represents "object_1" string

globals()[globals()['object']] represents object_1 object.

Brian
  • 12,145
  • 20
  • 90
  • 153