I’ve come across some code where square brackets are used on “self”. I’m not familiar with this notation and as I’m trying to get my head around source code not written by me, it makes it difficult to understand what sort of object is being dealt with here.
The example I’ve come across is in the Natural Language Toolkit for Python here. You can find an example of what I mean if you ctrl-F self[context].
It may not be possible to tell exactly how it’s being used without more context, but here’s a snippet with an example:
context = tuple(context)
if (context + (word,) in self._ngrams) or (self._n == 1):
return self[context].prob(word)
else:
return self._alpha(context) * self._backoff.prob(word, context[1:])
square brackets are python’s way of saying “call the
__getitem__(or__setitem__) method.”In your case, there’s nothing different between
selfanda. In fact, there’s nothing special aboutselfin a class’s method at all. The first argument passed to a method is an instance of the class, but you can call that argument anything you want.selfis just a (very highly recommended) convention.