Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does self[] mean in a method?

When reading a python program, I once find a function uses self in the following way.

class Auto(object):
   _biases_str = "biases{0}"

   def _b(self, n, suffix=""):
     name_b_out = self._biases_str.format(i + 1) + "_out"
     return `self[self._biases_str.format(n) + suffix]`

The line of name_b_out = self._biases_str.format(i + 1) + "_out" looks usual to me, i.e., we always self. to define something. But I am not very clear about the usage of self[self._biases_str.format(n) + suffix]. In specifc, what does self[] mean here, or what does it do?

like image 923
user785099 Avatar asked Feb 07 '23 06:02

user785099


1 Answers

It doesn't mean anything other than what variable[something] would mean. In Python variable[something] in an expression will just call variable.__getitem__(something), and self is the name conventionally used for the current object, or the receiver, in Python, so self[self._biases_str.format(n) + suffix] would mean pretty much the same as self.__getitem__(self._biases_str.format(n) + suffix)

I guess there is a method __getitem__ defined for that class as well.

like image 164