Getting attribute from other file using a variable?

Getting attribute from other file using a variable?

How do I put a variable into "getattr" to call an attribute from another file (in python 3)? The only thing I can think of gives a syntax error:

File1:

class Test:
    def __init__(self, test1, test2):
        self.test1 = test1
        self.test2 = test2

a = Test("test", "test")

File2:

import File1

def something(name):
    b = getattr(File2.{name}, test1)

It needs to be in a function for the purpose I am using it for, but the curly braces gives syntax error. Is there any way that something like this would work?

Answer

You probably want to get the attribute of the instance of Test from File1

def something(name):
    b = getattr(File1.a, name)  # instance of Test is named "a"
    return b

to get the whole instance a of Test from File1, you can use the same strategy .. however, you should also consider defining the __repr__ method of Test1 so it can be represented

# File1.py
class Test:
    def __init__(self, test1, test2):
        self.test1 = test1
        self.test2 = test2

    def __repr__(self):
        return "I'm an instance of Test!"

a = Test("test", "test")
# File2.py
import File1

def something(name):
    b = getattr(File1.a, name)  # instance of Test is named "a"
    return b

def something2(name):
    return getattr(File1, name)


print(something("test1"))  # use getattr to get name a.test1
print(something2("a"))     # get the entire instance of "a"
$ python3 ./File2.py
test
I'm an instance of Test!

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions