Call other methods within the class
Not only we can refer to instance variables inside a class using self.variable
, we can also access other methods inside the same class.
Again, self
is how we refer to things in the class from within itself (such as self.variable
and self.method
).
We will use an example to show how to access other methods inside the same class.
Marble_bag class
(remember docstring? Class can have docstring to explain itself) :
# Marble_bag
class Marble_bag:
"""I have some base marbles in my bag.
I put more and more marbles into my bag."""
def __init__(self, base):
self.total = base
def put(self, m):
self.total += m
return self.total
def putTwice(self, n):
self.put(n)
self.put(n)
return self.total
Here in Marble_bag
class, in __init__
, we define object variable using self.total
and assign a value base
to it as the base number of the marbles.
Then we define the second method put(self, m)
, in put()
, we refer to object variable total
using self.total
.
The same thing, in the third method putTwice(self, n)
, we may call other method(put(self,m)
) inside the same class by using self.put(n)
. The self
indicates that put()
is of the same object as putTwice()
is called on.
Please note
when we call
self.put(n)
, we only provide value(n
) for variablem
specified input(self, m)
, no need to provide value for parameterself
Let's make a Marble_bag
object:
# create a new object 'myBag'
myBag = Marble_bag(5)
print( myBag.total ) # 5 (base number)
myBag.put(10)
print( myBag.total ) # 15 (total: 5 + 10 )
myBag.putTwice(15)
print( myBag.total ) # 45 (total: 5+10+15+15 )
First, we create a Marble_bag
instance: named it myBag
, and initialize it with value 5
, so we have base number: 5 marbles in myBag
.
Then we call the method put(10)
to put more marbles in myBag
. When we call the methods of the object, we don't need to include the self
argument, only provide value for other input argument. Now the total
is 15
.
Last, we call another method putTwice(15)
, this method in turn calls put(15)
of the same object twice using self.put(15)
to put 15
and another 15
in this object. So myBag
now has total
of 45
marbles ( 5+10+15+15
)