Syllabus Lesson 49 of 239 · Object-Oriented Python
Object-Oriented Python

Methods and self

Attributes are the data an object holds. Methods are the things an object can do. A method is just a function defined inside a class, and like __init__ its first parameter is self so it can read and change the object's own data.

class Counter:
    def __init__(self):
        self.count = 0

    def increment(self):
        self.count = self.count + 1

    def value(self):
        return self.count

c = Counter()
c.increment()
c.increment()
print(c.value())   # 2

You call a method with a dot, the same way you read an attribute, but with parentheses: c.increment(). Again you do not pass self, Python passes the object on the left of the dot in for you.

Methods can take extra parameters too, and they can use other attributes on self:

class Greeter:
    def __init__(self, greeting):
        self.greeting = greeting

    def greet(self, name):
        return f"{self.greeting}, {name}!"

g = Greeter("Hi")
print(g.greet("Sam"))   # Hi, Sam!

A method that returns a value uses return, just like a normal function.

Your turn

Define a class BankBox with __init__ that sets self.total to 0. Add a method add(self, amount) that increases self.total by amount, and a method balance(self) that returns self.total. The starter creates a box, adds 10 then 5, and you must make balance() return 15.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output