0

I need to get the attribute of different objects to print your content. I thought about using the object argument dynamically, is it possible?

content = getattr("%s" % (variable), "attribute")
Rarblack
  • 4,559
  • 4
  • 22
  • 33
  • Not quite sure what your actual question is. – de1 Oct 08 '18 at 12:53
  • I think you're trying to do this? [How to get the value of a variable given its name in a string?](//stackoverflow.com/q/9437726) – Aran-Fey Oct 08 '18 at 12:54
  • no that does not work (your solution, the previous comment works perfectly), you need the object not a string with the object name, try something like getattr(globals()[variable], "attribute_name") – E.Serra Oct 08 '18 at 12:55
  • 3
    If you have the name of a variable in a string, you're already doing it wrong. – chepner Oct 08 '18 at 13:15

1 Answers1

0

Do you mean something like this?

class Custom:
    def __init__(self):
        self.pet = 'dog'

my = Custom()

variable = 'my'
print(getattr(globals()[variable], 'pet'))

Output:

dog
Hkoof
  • 756
  • 5
  • 14