liveBook · Manning

Method

As explained in Practices of the Python Pro

A method is a function associated with a class or object and typically invoked through that association.

A method is a function contained in a class. It describes behavior for objects created from that class and commonly receives the instance as an additional Python argument named self. Through self, a method can read or change the object’s attributes, or state. section 2.2.2 section 3.2.1

Methods become useful when several functions repeatedly share data or pass results between one another. Grouping those related behaviors with their data in a class gives the object a focused set of responsibilities instead of leaving loosely connected functions scattered through the program. section 2.2.2 section 3.2.1

Turning game functions into methods

A Rock, Paper, Scissors simulator can move functions such as get_computer_choice(), print_options(), and print_choices() inside a RockPaperScissorsSimulator class. Each method then uses self where it needs the simulator instance. An __init__ method can establish self.computer_choice and self.human_choice before simulate() coordinates the steps. The object is used as RPS = RockPaperScissorsSimulator(); RPS.simulate(). section 2.2.2

Listing 2.4. Moving functions into a class as methods
import random

OPTIONS = ['rock', 'paper', 'scissors']


class RockPaperScissorsSimulator:
    def get_computer_choice(self):                               #1
        return random.choice(OPTIONS)

    def get_human_choice(self):
        choice_number = int(input('Enter the number of your choice: '))
        return OPTIONS[choice_number - 1]

    def print_options(self):
        print('\n'.join(f'({i}) {option.title()}' for i,
 option in enumerate(OPTIONS)))

    def print_choices(self, human_choice, computer_choice):      #2
        print(f'You chose {human_choice}')
        print(f'The computer chose {computer_choice}')

    def print_win_lose(self, human_choice, computer_choice,
 human_beats, human_loses_to):
        if computer_choice == human_loses_to:
            print(f'Sorry, {computer_choice} beats {human_choice}')
        elif computer_choice == human_beats:
            print(f'Yes, {human_choice} beats {computer_choice}!')

    def print_result(self, human_choice, computer_choice):
        if human_choice == computer_choice:
            print('Draw!')

       if human_choice == 'rock':
           self.print_win_lose('rock', computer_choice, 'scissors', 'paper')
        elif human_choice == 'paper':
           self.print_win_lose('paper', computer_choice, 'rock', 'scissors')
        elif human_choice == 'scissors':
           self.print_win_lose('scissors', computer_choice, 'paper', 'rock')

Inspect the short refactoring example to see ordinary functions become class methods and receive self. section 2.2.2

A method can also help control an interface. In a Greeter class, _day() and _part_of_day() can remain internal helpers while greet() exposes the main operation. This keeps callers focused on greeting rather than on the details used to construct the message. section 3.3

How Practices of the Python Pro covers it

How deep it goes
Explains method placement, self, instance state, __init__, and internal helpers through short Python examples.
Examples
Demonstrates methods with a Rock, Paper, Scissors simulator and a Greeter class exercise.
What it assumes
Assumes familiarity with Python functions and introduces classes, objects, attributes, self, and __init__ progressively.
What you can do after
Build it from scratch by moving related functions into classes, using self for state, and exposing a focused operation.
How it connects
Connects methods with functions, classes, objects, attributes, encapsulation, modules, and packages.

Also explained in

Compare how 20 books explain method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.