I want to call some unknown function with adding parameters using getattr function. Is it possible?
getattr() is one of the coolest built-in functions in Python. It takes three arguments: an object. name of the object's attribute but in the string format.
Putting it to work: generalizing method calls Okay, so it's cool that you can use getattr to get methods as well as properties, but how does that help us? Well, this can definitely be useful in keeping your code DRY if you have some common logic surrounding branching method calls.
The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.
Yes, but you don't pass them to getattr()
; you call the function as normal once you have a reference to it.
getattr(obj, 'func')('foo', 'bar', 42)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With