Is it possible to access a property/method on a Python object with a variable and how?
Example:
handler.request.GET.add()
I'd like to replace the 'GET' part by capturing the method beforehand into a variable and then using it in the dot notation.
method = handler.method
handler.request.{method}.add()
I just can't see where/how to do that.
Object.assign() Method Among the Object constructor methods, there is a method Object. assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target.
Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
Dot notation is one way to access a property of an object. To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property. Example: var cat = { name: 'Moo', age: 5, }; console.
Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.
You are looking for getattr
:
getattr(handler.request, 'GET')
is the same as handler.request.GET
.
So you can do
method = "GET"
getattr(handler.request, method).add()
Use the getattr()
function to access dynamic attributes:
method = 'GET'
getattr(handler.request, method).add()
which would do exactly the same thing as handler.request.GET.add()
.
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