liveBook · Manning

Method

As explained in Get Programming: Learn to code with Python

A method is a function defined as part of an object type that can operate on the object instance through its parameters.

A method is a function defined inside a class. It gives objects of that class an operation they can perform. A Circle, for example, can have methods to change its radius or report it. section 31.2 section 31.3

class Circle(object):
    def __init__(self):
        self.radius = 0
    def change_radius(self, radius):
        self.radius = radius
    def get_radius(self):
        return self.radius

The Circle class places three methods together: __init__ sets the starting radius, change_radius changes it, and get_radius returns it. section 31.2 section 31.3

A method's first parameter is self, a placeholder for the object it acts on. Inside a method, self.radius accesses that object's radius. When you call one_circle.change_radius(4), you supply 4 but not self: Python uses one_circle for self. Another Circle keeps its own radius. You can also write the call explicitly as Circle.change_radius(one_circle, 4). section 31.4 section 31.6

A stack of pancakes

A Stack uses a list to hold its items. After pancakes = Stack(), calls such as pancakes.add_one("blueberry"), pancakes.add_many("chocolate", 4), and pancakes.remove_one() operate on that stack. Its size method returns a value; its prettyprint method prints items instead. Try designing a queue next: what methods would let someone add, remove, and show its items? section 32.1 section 32.2 section 32.3

Choose methods by asking what an object should do and how others will use it. Keeping an object's data and operations together also makes larger programs easier to organize: gameplay code can call a method without repeating its implementation. section 32.1 section 34.6

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains method definitions, self, attribute access, instance calls, and equivalent explicit class-name calls.
Examples
Demonstrates Circle radius methods and Stack operations on pancake strings and Circle objects.
What it assumes
Builds on functions and parameters while defining methods, self, and object attributes explicitly.
What you can do after
Build it from scratch: define methods for object types, call them on instances, and test circle, rectangle, or queue operations.
How it connects
Connects methods to classes, instances, data attributes, initialization, and stacks.

Also explained in

Compare how 20 books explain method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.