[Tutor] names and variables

Marc Tompkins marc.tompkins at gmail.com
Wed Aug 20 11:37:23 CEST 2008


On Wed, Aug 20, 2008 at 2:30 AM, Jim Morcombe <jmorcombe at westnet.com.au>wrote:

> I have an object called "myObject" with an attribute called "colour".
>
> If  I type:
>   print myObject.colour
> then python prints:
>    red
>
> Now, I have a variable "myAttribute" and set its value to "colour" by
> typing:
>   myAttribute = "colour"
>
> I want to have a line of code:  something like this:
>   print myObject.myAttribute
> and have Python interpret it as meaning "print myObject.colour" and hence
> print "red"
>
>
> Can this be done?  If so, how?
>
> Jim Morcombe
>

print(getattr(myObject, "colour"))

Here's the effbot article:  http://effbot.org/zone/python-getattr.htm

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080820/95e4d717/attachment-0001.htm>


More information about the Tutor mailing list