The right way to 'call' a class attribute inside the same class

Chris Angelico rosuav at gmail.com
Sun Dec 18 18:04:44 EST 2016


On Mon, Dec 19, 2016 at 9:52 AM, Erik <python at lucidity.plus.com> wrote:
>
> 1) Method call:
>    "obj.foo(1, 2, 3)" is syntactic sugar for "obj.foo(obj, 1, 2, 3)".

And the bit you have to be REALLY careful of when working with both
Python and JS is that you have to have "obj.foo(...)" as a single
expression. Consider:

# Python
lst = []
func = lst.append
func(1); func(2); func(3)
# lst now holds [1,2,3]

// JavaScript
var arr = []
var func = arr.push.bind(arr) // IMPORTANT
func(1); func(2); func(3)
// arr now contains [1,2,3]

If you just take "arr.push", you don't get a bound method. You get an
unbound method. You have to explicitly bind that back to the array
object, or its "this" pointer won't be set.

This is so important (eg with callback functions) that JS introduced a
new type of function to help deal with the problem...

ChrisA



More information about the Python-list mailing list