On Wed, 2008-08-20 at 11:37 +0200, [EMAIL PROTECTED] wrote: > Message: 7 > Date: Wed, 20 Aug 2008 17:30:37 +0800 > From: Jim Morcombe <[EMAIL PROTECTED]> > Subject: [Tutor] names and variables > To: tutor@python.org > Message-ID: <[EMAIL PROTECTED]> > 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. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor