Recently I come across the following code in python
for var in self:
self.some_list.append(var)
I know little about self but the above code really made me to think so can some one explain me what the piece of code mean ?
Recently I come across the following code in python
for var in self:
self.some_list.append(var)
I know little about self but the above code really made me to think so can some one explain me what the piece of code mean ?
The identifier self
has no special meaning in python, it can hold whatever you put into it (either via an assignment or an argument of a function).
The only thing is that instance method when called will put the object on which the method was called as the first argument which is normally (by convention) called self
.
When you iterate over some object with the for ... in ...
syntax, you are really calling the __iter__
method of it. For example,
class Iterable(object):
def __init__(self, *args):
self.items = args
def dump(self):
for val in self:
print 'I have %s!' % str(val)
def __iter__(self):
for val in self.items:
yield val
i = Iterable(1, 2, 3, 'foo', 'bar')
i.dump()
In the dump
method the for val in self
iterates over the self.values
list as implemented by __iter__
. If you drop the __iter__
method, Python won't know what to do and you will get a TypeError ('Iterable' object is not iterable).