Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square brackets applied to "self" in Python

Tags:

python

nlp

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:])
like image 746
user1002973 Avatar asked Dec 17 '12 21:12

user1002973


1 Answers

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.

like image 199
mgilson Avatar answered Oct 01 '22 17:10

mgilson