Can you please clarify how it is that self.add(x) below works the same way as self.data.append(x)?
That is, how does self.add(x) know to append to the list because we have not explicitly stated self.data.add(x)? When we state y.addtwice('cat'), 'cat' is added to 'self', not self.data.
class Bag:
def __init__(self):
self.data=[]
def add(self,x):
self.data.append(x)
return self.data
def addtwice(self,x):
self.add(x)
self.add(x)
return self.data
>>> y = Bag()
>>> y.add('dog')
['dog']
>>> y.addtwice('cat')
['dog', 'cat', 'cat']
Because
addtwicecalls methods which are defined on self, and because self.data is a “mutable type”, addtwice’s call to add will end up appending the value of self.data.add, in turn calls self.data.appendWhen calling a function in a computer program, you can think of the process as being a series of substitutions like this:
self, itself, is never really appended in any of those cases though.self.datais.