liveBook · Manning

Method

As explained in Python Workout, Second Edition

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

A method is a function associated with an object or class and invoked through that association. It packages behavior with the data it operates on. section 10.1

Define methods inside a class. Python passes the invoked instance as the first argument, conventionally named self, so the method can read or change attributes such as self.flavor. The name self is a convention rather than a reserved word, but tools and Python programmers expect it. section 10.6

Move an operation onto its data

A standalone average(numbers) function leaves callers responsible for supplying and understanding a list. A ScoreList class can store the scores and expose average() directly: scores = ScoreList([...]); scores.average(). The calculation stays the same, while the interface expresses the domain more clearly. section 10.1

When implementing or using methods, remember:

  • Put the instance parameter first and normally call it self; include additional parameters for the operation's inputs. section 10.6
  • Use methods to express relationships between objects, such as Shelf.add_book, Shelf.has_book, and Shelf.total_price. section 10.12
  • Practice methods alongside attributes, composition, inheritance, and class-level behavior when building Python objects. section 10.3
class ScoreList():
    def __init__(self, scores):
        self.scores = scores

    def average(self):
        return sum(self.scores) / len(self.scores)

scores = ScoreList([85, 95, 98, 87, 80, 92])
print(f'The final score is {scores.average()}.')

Compare a regular function with a method attached to ScoreList and invoked through an instance. section 10.1

How Python Workout, Second Edition covers it

How deep it goes
Explains definition, invocation, self, attributes, composition, and inheritance, without descending into method-dispatch internals.
Examples
Uses score averaging, Shelf operations, Scoop initialization, string uppercasing, and inherited x2 and x3 methods.
What it assumes
Assumes regular Python functions and basic syntax while teaching objects, classes, attributes, self, composition, and inheritance.
What you can do after
Build it from scratch by defining classes with methods, storing instance data, and invoking behavior through objects.
How it connects
Connects methods with objects, classes, functions, attributes, composition, inheritance, and object-oriented programming.

Also explained in

Compare how 20 books explain method →

Related concepts

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