4. Methods
A method is a function defined inside a class. It receives the instance as its first parameter, by convention named self:
barkis a method: notice that it is indented inside the class, at the same level as__init__.- When you call
dog.bark(), Python passesdogasselfautomatically. You write no argument forself. - Inside the method,
self.namereads the attribute of that same instance.
Methods can take extra parameters. They come after self, and you pass them normally:
- The definition has two parameters:
selfandname. - The call has one argument:
"Ada".selfis automatic.
A method can return a value, exactly like a function, and it can change the instance's attributes:
Coming from JavaScript? Methods are like class methods, but this is not implicit: you write self as the first parameter and use self.attribute. Calling obj.method() is the same.
Call a method
Define a class Greeter with a method hello(self) that prints Hello!. Create greeter = Greeter() and call greeter.hello().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read an attribute inside a method
Define Dog with __init__(self, name) that stores self.name, and a method bark(self) that prints <name> says woof, using self.name. Create dog = Dog("Rex") and call dog.bark().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
A method with an extra parameter
Define a class Greeter with a method greet(self, name) that prints Hello, <name>!. Create greeter = Greeter() and call greeter.greet("Ada").
The call passes one argument; self is filled in automatically.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Return a value from a method
Define Rectangle with __init__(self, width, height) that stores both attributes. Add a method area(self) that returns self.width * self.height. Create rectangle = Rectangle(2, 3) and print rectangle.area().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Change the instance from a method
Define Counter with __init__(self) that sets self.value = 0, and a method increment that adds 1 to self.value. Create counter = Counter(), call counter.increment() twice, then print counter.value.
Print exactly:
Create a free account to save your progress and unlock chapter 2.