liveBook · Manning

Self parameter

As explained in Get Programming: Learn to code with Python

self is the conventional first parameter of a Python instance method that refers to the instance on which the method is called.

self is the conventional first parameter of a Python instance method. It refers to whichever object receives the method call, so self.radius means that particular circle's radius. Think of self as a placeholder for the instance being created or used. section 31.2

A circle remembers its own radius

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 first method creates a radius attribute for each Circle. change_radius updates the current object's radius, while get_radius returns it. In one_circle.change_radius(4), Python supplies one_circle as self; 4 supplies the radius parameter. section 31.3 section 31.4

Keep these three uses separate:

  • Declare self first in an instance method, even when the method needs no other parameter. section 31.2 section 31.3
  • Use self.attribute to store or access data belonging to the current object. section 31.2
  • Pass only the method's additional arguments at the call site; Python automatically supplies self from the object before the dot. section 31.4
  • Remember that each instance has separate self-defined attributes, so changing one circle does not change another. section 31.4
class Circle(object):
    def __init__(self):
        self.radius = 0

Inspect the smallest complete example: __init__ uses self.radius to give every Circle instance its own starting radius. section 31.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains declarations, attribute access, automatic argument assignment, and per-instance effects through small class examples.
Examples
Uses Circle and Door classes, radius attributes, method calls, independent instances, and short method-writing exercises.
What it assumes
Assumes basic function and parameter familiarity while introducing classes, objects, instances, and data attributes together.
What you can do after
Build instance methods that initialize, change, retrieve, and calculate values stored on individual objects.
How it connects
Connects self with classes, instances, instance methods, data attributes, __init__, and dot notation.

Also explained in

Compare how 3 books explain self parameter →

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.