Python
class property
string access
duplicate
Python programming

Python access class property from string

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If you have the name of an attribute as a string in Python, the normal way to read it is getattr. This shows up in serializers, command dispatchers, templating helpers, and configuration-driven code. The important part is understanding when dynamic attribute access is appropriate and when it becomes too implicit or unsafe.

The Straightforward Tool: getattr

getattr(obj, name) returns the attribute named by the string name.

python
1class User:
2    def __init__(self, username, score):
3        self.username = username
4        self.score = score
5
6
7user = User("mark", 42)
8field = "score"
9
10print(getattr(user, field))

This prints 42.

You can also provide a default value so missing attributes do not raise AttributeError:

python
1class User:
2    def __init__(self, username):
3        self.username = username
4
5
6user = User("mark")
7
8print(getattr(user, "username", None))
9print(getattr(user, "email", None))

That is often better than writing a manual if ladder when the attribute name is truly dynamic.

Properties Work Too

In Python, a property is still accessed like an attribute from the outside, so getattr works with @property the same way it works with plain instance attributes.

python
1class Product:
2    def __init__(self, price, tax_rate):
3        self.price = price
4        self.tax_rate = tax_rate
5
6    @property
7    def total(self):
8        return self.price * (1 + self.tax_rate)
9
10
11product = Product(100, 0.2)
12print(getattr(product, "total"))

That matters because the string-driven code does not need to care whether the attribute is stored directly or computed through a property.

When __dict__ Is Not the Right Answer

Developers sometimes try to use obj.__dict__[name]. That works only for attributes stored directly on the instance dictionary. It does not handle:

  • properties
  • descriptors
  • inherited attributes
  • methods
  • objects using __slots__

For example:

python
1class Example:
2    @property
3    def answer(self):
4        return 42
5
6
7obj = Example()
8print(getattr(obj, "answer"))
9print(obj.__dict__)

getattr returns the property value, while __dict__ does not contain it. That is why getattr is usually the correct general-purpose tool.

Accessing Methods by Name

Dynamic lookup also works for methods. The retrieved method is a bound method when accessed through an instance, which means you can call it directly.

python
1class Greeter:
2    def hello(self, name):
3        return f"Hello, {name}"
4
5
6greeter = Greeter()
7method_name = "hello"
8method = getattr(greeter, method_name)
9
10print(method("Ada"))

This is useful for command dispatch patterns:

python
1class CommandHandler:
2    def run_start(self):
3        return "starting"
4
5    def run_stop(self):
6        return "stopping"
7
8
9handler = CommandHandler()
10action = "start"
11result = getattr(handler, f"run_{action}")()
12print(result)

The pattern is compact, but it should be constrained carefully if the input comes from outside the program.

Safer Dynamic Access

If attribute names come from users, APIs, or configuration files, avoid exposing the entire object surface. Whitelist the names you support.

python
1class User:
2    def __init__(self, username, score):
3        self.username = username
4        self.score = score
5
6
7SAFE_FIELDS = {"username", "score"}
8
9
10def read_field(obj, field_name):
11    if field_name not in SAFE_FIELDS:
12        raise ValueError("unsupported field")
13    return getattr(obj, field_name)
14
15
16user = User("mark", 42)
17print(read_field(user, "username"))

This keeps the dynamic behavior but avoids accidental access to internal attributes such as dunder names or helper methods.

Reading Versus Writing

If you need to change an attribute by string name, use setattr:

python
1class User:
2    def __init__(self):
3        self.score = 0
4
5
6user = User()
7setattr(user, "score", 99)
8print(user.score)

hasattr is also available when you only need an existence check:

python
print(hasattr(user, "score"))
print(hasattr(user, "email"))

These three functions form the core toolkit for dynamic attribute access in Python.

When Not to Use Dynamic Attribute Access

Do not use string-based lookup just because it feels clever. It is the right tool only when the attribute name is naturally data-driven. If the set of fields is fixed and small, explicit code is usually easier to read and easier to refactor.

Dynamic lookup is powerful, but it reduces static discoverability. That tradeoff is worth making only when the input is genuinely dynamic.

Common Pitfalls

  • Using obj.__dict__[name] as a general replacement for getattr. It misses properties, methods, and inherited attributes.
  • Calling getattr on untrusted names without validation. That can expose more of the object than intended.
  • Forgetting the default argument. If missing attributes are acceptable, pass a fallback instead of catching AttributeError everywhere.
  • Overusing dynamic lookup when a simple explicit branch would be clearer.
  • Confusing reading with writing. Use getattr for reads and setattr for updates.

Summary

  • Use getattr(obj, name) to access an attribute whose name is stored in a string.
  • 'getattr works for regular attributes, properties, and bound methods.'
  • Prefer it over direct __dict__ access for general attribute lookup.
  • Whitelist allowed names when the string comes from external input.
  • Use setattr and hasattr for the matching write and existence-check operations.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.