[Tutor] names and variables
Lie Ryan
lie.1296 at gmail.com
Wed Aug 20 12:54:39 CEST 2008
On Wed, 2008-08-20 at 11:37 +0200, tutor-request at python.org wrote:
> Message: 7
> Date: Wed, 20 Aug 2008 17:30:37 +0800
> From: Jim Morcombe <jmorcombe at westnet.com.au>
> Subject: [Tutor] names and variables
> To: tutor at python.org
> Message-ID: <48ABE43D.1010305 at westnet.com.au>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> 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?
>
Do you mean this:
>>> class A(object): pass
...
>>> class A(object):
... colour = 'red'
...
>>> a = A()
>>> def getcolour(self):
... print self.colour
>>> A.myAttribute = getcolour
>>> a.myAttribute()
'red'
Of course, this is why python's is called dynamic language: the ability
to change a class' definition on runtime, even on an already
instantiated objects.
More information about the Tutor
mailing list