Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying object property in dot notation with a variable

Tags:

python

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.

like image 833
jturmel Avatar asked Feb 03 '13 22:02

jturmel


People also ask

How do you assign a value to an object property?

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.

Which notation is used to access variables of objects?

Property accessors provide access to an object's properties by using the dot notation or the bracket notation.

How do you write dot 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.

How is an object property referenced?

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.


2 Answers

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()
like image 153
BrenBarn Avatar answered Sep 28 '22 10:09

BrenBarn


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().

like image 40
Martijn Pieters Avatar answered Sep 28 '22 08:09

Martijn Pieters