[Tips] How To Get Attribute By String In Python


Today’s goal is to access attributes of objects by the string of its name.
What I’d like to do is the following.

class MyClass:
  class_attr = 1
  def __init__(self, num):
    self.attr1 = 100 + num
    self.attr2 = 200 + num
  def func1(self):
    print("this is func1")
item = MyClass(5)
attr = "attr2"
print(item.get_attr(attr)) # output should be 205


Python 3.8.7


Use getattr(objectname) to get attributes. And setattr(objectname) to set attributes.

item = MyClass(5)
attr = "attr2"
print(getattr(item, attr))
# output => 205

You can get methods and class variable too.

getattr(item, "func1")()
# output => this is func1

print(getattr(MyClass, "class_attr"))
# output => 1