1.5 KiB
1.5 KiB
id, source_exercise_id, title, section, source_path, source_repo, source_commit, student_visible_solution, has_private_solution, skip
| id | source_exercise_id | title | section | source_path | source_repo | source_commit | student_visible_solution | has_private_solution | skip |
|---|---|---|---|---|---|---|---|---|---|
| practical-python-5.4 | 5.4 | Bound methods | 5.1 Dictionaries Revisited | 05_Object_model/01_Dicts_revisited.md | https://github.com/dabeaz-course/practical-python | 93dca856b41c61a0a0f85ae334116e4c125629ea | false | false | false |
Exercise 5.4: Bound methods
Source: Practical Python Programming,
05_Object_model/01_Dicts_revisited.md.
Exercise 5.4: Bound methods
A subtle feature of Python is that invoking a method actually involves two steps and something known as a bound method. For example:
>>> s = goog.sell
>>> s
<bound method Stock.sell of Stock('GOOG', 100, 490.1)>
>>> s(25)
>>> goog.shares
75
>>>
Bound methods actually contain all of the pieces needed to call a method. For instance, they keep a record of the function implementing the method:
>>> s.__func__
<function sell at 0x10049af50>
>>>
This is the same value as found in the Stock dictionary.
>>> Stock.__dict__['sell']
<function sell at 0x10049af50>
>>>
Bound methods also record the instance, which is the self
argument.
>>> s.__self__
Stock('GOOG',75,490.1)
>>>
When you invoke the function using () all of the pieces come
together. For example, calling s(25) actually does this:
>>> s.__func__(s.__self__, 25) # Same as s(25)
>>> goog.shares
50
>>>