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."
x = a[...] #call a.__getitem__(...)
a[...] = x #call a.__setitem__(...)
del a[...] #call a.__delitem__(...)
In your case, there's nothing different between self
and a
. In fact, there's nothing special about self
in 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. self
is just a (very highly recommended) convention.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With