Last active
November 22, 2023 16:01
-
-
Save Wilfred/49b0409c6489f1bdf5a5c98a488b31b5 to your computer and use it in GitHub Desktop.
dynamically defined properties in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def attach_dyn_prop(instance, prop_name, prop_fn): | |
"""Attach prop_fn to instance with name prop_name. | |
Assumes that prop_fn takes self as an argument. | |
Reference: https://stackoverflow.com/a/1355444/509706 | |
""" | |
class_name = instance.__class__.__name__ + 'Child' | |
child_class = type(class_name, (instance.__class__,), {prop_name: property(prop_fn)}) | |
instance.__class__ = child_class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment