[Tutor] Associate functinos with Dictionary/Class Usage
Luke Jordan
luke.jordan at gmail.com
Fri Apr 8 19:37:29 CEST 2005
Yes, Danny - that makes sense. I was getting hung up how to handle the
parens in this part
dict['some'](thing)
all clear now.
:-)
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!
>
>
--
"Scalpel....blood bucket....priest....next patient."
More information about the Tutor
mailing list