[Tutor] Associate functinos with Dictionary/Class Usage

Shane Liebling shanel at gmail.com
Sat Apr 9 21:38:54 CEST 2005


Although I was not the questioner, I must admit this was a brief but
efficient answer.  Reminds me to try something like the last part out
some time...

-Shane

On Apr 7, 2005 4:40 PM, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
> 
> 
> On Thu, 7 Apr 2005, Luke Jordan wrote:
> 
> > I am looking for a little clarification of how exactly this would work.
> >
> > 1. How do I associate a function to a dict key?
> 
> Hi Luke,
> 
> We're probably already familiar of values like numbers and strings, and
> how to give them names with variables:
> 
> ######
> >>> number = 42
> >>> name = "luke"
> >>> number
> 42
> >>> name
> 'luke'
> ######
> 
> 'number' is a name that refers to the value 42, and 'name' is a name (Doh!
> I must use a better variable name next time...) that refers to the value
> "luke".
> 
> And we also already know how to make functions and to call them:
> 
> ######
> >>> def square(x):
> ...     return x * x
> ...
> >>> square(42)
> 1764
> ######
> 
> But what happens if we just say "square" at the interpreter?
> 
> ######
> >>> square
> <function square at 0x40300b1c>
> ######
> 
> The value of 'square' is a function value.
> 
> And just like any other value, we can assign it to another name:
> 
> ######
> >>> anotherNameForSquare = square
> >>> anotherNameForSquare(16)
> 256
> ######
> 
> And just like any other value, we can use it as a dictionary value:
> 
> ######
> >>> operators = {'^2': square}
> >>> operators['^2']
> <function square at 0x40300b1c>
> >>> operators['^2'](4)
> 16
> ######
> 
> Does this make sense so far?  Please feel free to ask more questions about
> this.  Best of wishes!
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
Shane Liebling
Systems Administrator and SAGE Member


More information about the Tutor mailing list