Python: access class property from string
To access a class property using a string name, use Python's built-in getattr
function. Here's a quick example:
In this line, getattr(instance, 'property_name')
, we're poking around instance
to snatch the my_property
's value. And voilà! We got "value"
.
Additionally, you can modify or delete class properties with setattr(instance, 'property_name', new_value)
and delattr(instance, 'property_name')
, respectively.
Mastering dynamic attribute access
Setting properties: setattr()
In addition to getattr
for accessing properties, you can use setattr
for setting them dynamically:
This command turns the my_property
into "new_value"
, giving us a brilliant display of attribute metamorphosis. Remember though, with great power comes great data integrity responsibility!
Deleting attributes: delattr()
Ever need to bid adieu to a class property? Use delattr
:
Abruptly, instance
no longer carries my_property
, helpful for handling ephemeral or context-sensitive properties.
Unfounded attributes and default values
In cases where getattr
can't locate the attribute, it raises an AttributeError
. To bypass this hiccup, supply a default value:
If non_existent_property
continues to elude us, "default"
calmly steps in, providing safe passage through error-prone terrain.
Dictionaries: An alternative attribute container
If dynamic attribute access via getattr
isn't sufficient, consider bundling attributes into a dictionary for more structured, string-keyed access:
Here, get_property
serves as a safe harbor, returning a default value when the sought property hides.
Broader horizons: Exploring attribute handling
Embracing dictionary-like object access
For a more intuitive workflow, Python allows overloading the __getitem__
method to enable dictionary-like property access:
In this setup, we're augmenting our class with a custom __getitem__
method that leverages getattr
, offering that sweet, familiar dictionary syntax.
Attribute existence check: hasattr()
To avoid unexpected errors, check attribute existence with hasattr
before accessing or setting it:
Alright detectives, this tight pattern ensures no non-existent attribute can surprise us!
Was this article helpful?